【问题标题】:PHP Parsing HTML to multidimensional JSON ArrayPHP 将 HTML 解析为多维 JSON 数组
【发布时间】:2017-06-06 18:37:00
【问题描述】:

我正在解析 HTML 并将多维输出数组作为 json。 我正在解析我想要的 html,但我无法创建 JSON 数组。

foreach 循环的示例输出:

PS:每个 json 对象都有不同的字符串值。

0:"废话"

1:“废话”

2:“废话”

3:“废话”

4:" " // 只有空格

5:“废话”

6:“废话”

7:“废话”

8:“废话”

9:" " // 只有空格

...

我想创建这样的 json 数组:

 $output = array();
    $html = str_get_html($ret);

    $lessons["lesson"] =array();
    foreach($html->find('table//tbody//tr') as $element) {

        $temp = strip_tags($element->innertext);

        array_push($lessons['lesson'], $temp); // the objects (I wrote as 'blahblah' every object but I getting different values always)

        if($temp == " ") // if there is only space push array the output and create new array
        {

            array_push($output , $lessons["lesson"]);
            unset($lessons);
            $lessons["lesson"] = array();
        }
    }
echo (json_encode($output ,JSON_UNESCAPED_UNICODE)); // $output show nothing

感谢您的建议。

【问题讨论】:

    标签: php arrays json multidimensional-array


    【解决方案1】:

    如果您的问题是将所有内容都放入数组中,那么下面的内容将带您到达那里。我没有很好地遵循代码,但尝试在 cmets 中解释我的想法。

    $json = ["blahblah"
    ,"blahblah"
    ,"blahblah"
    ,"blahblah"
    ," "
    ,"blahblah"
    ,"blahblah"
    ,"blahblah"
    ,"blahblah"
    ," "];
    
    
    $lessons["lesson"] = []; // I think this is the array you are using
    $tmp = []; // Something tmp to hold things
    foreach($json as $elm){ //Loop what I assume $html->find('table//tbody//tr') is returning
        if($elm != ' '){//Wait for a ' ' and add to tmp
            $tmp[] = $elm;
        } else {
             $lessons["lesson"][] = $tmp; // This array is done so keep it and restart
             $tmp = [];
        }
    }
    

    【讨论】:

    • 谢谢!但是我将您的 if 子句更改为 "if($elm != ' ') 然后它起作用了!如果您像这样更新您的帖子,我会接受您的回答
    猜你喜欢
    • 1970-01-01
    • 2019-06-13
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    相关资源
    最近更新 更多