在PHP简单HTML DOM解析器中同时解析多个标签

时间:2016-03-07 11:16:32

标签: php parsing simple-html-dom

我试图将两个不同的标签内容保存在同一个" foreach"中的两个不同变量中。循环,但我在下面得到parse error

foreach( $days -> find('td[!width]') as $schedule) && ($days -> find('a') as $title ) {
        echo "<div class=\"movie_name\">"
        .$title->plaintext."</div> - <div class=\"movie_schedule\">"
        .$schedule->plaintext."</div>\n";
}

关于什么可能出错的任何想法?

*编辑*

我解决了将循环分成两个独立循环的问题,如下所示:

    $movie_titles = array();
    foreach($days -> find('a') as $title) {
        $movie_titles[] = $title->plaintext;
    }
    $counter = 0;
    foreach( $days -> find('td[!width]') as $schedule) {
        echo "<div class=\"movie_name\">"
        .$movie_titles[$counter]
        ."</div> - <div class=\"movie_schedule\">"
        .$schedule->plaintext."</div>\n";
        $counter = $counter + 1;
    }

不是很优雅,但它可以胜任。

1 个答案:

答案 0 :(得分:1)

foreach无法正常工作。仅

foreach ($array as $key => $value) {
    // ...
}

foreach ($array as $value) {
    // ...
}

你必须使用两个循环或完全不同的方法(取决于你的任务)。

foreach ($days->find('td[!width]') as $schedule) {
    foreach ($days->find('a') as $title) {
        echo "<div class=\"movie_name\">"
            . $title->plaintext."</div> - <div class=\"movie_schedule\">"
            . $schedule->plaintext."</div>\n";
    }
}