HTMLDOM嵌套div

时间:2016-07-23 07:17:41

标签: php laravel simple-html-dom

您好我正在使用laravel工作htmldom我的html如下所示

<div class="content">
    <h4 class="title">Now Showing</h4>
    <div class="movies">   
      <div class="movie">
         <h4 class="movie-title">3D: Star Trek Beyond</h4>
            <p class="movie-type">PG</p>
      </div>

      <div class="movie">
         <h4 class="movie-title">Movie 2</h4>
            <p class="movie-type">PG</p>
      </div>

   </div>

   <h4 class="title">Comming Soon</h4>
    <div class="movies">
       <div class="movie">
         <h4 class="movie-title">Some Other</h4>
         <p class="movie-type">PG</p>
       </div>

    </div>
</div>

我想要这样的输出

现在显示
 3D:Star Trek Beyond
 电影2

即将推出
其他一些

我试过

    foreach($html->find('div[class=content]') as $content)
        {
//tried this but it only return one item
//$heading = $content->find('h4[class=title]');

          foreach($content->find('div[class=movies]') as $movies)
          {
             foreach($movies->find('div[class=movie]') as $movie)
            {
               $info = $movie->find('h4[class=movie-title]');
               $movie_info[]=array(

                                        'title'=>$info[0]->innertext
                                    );
            }
           $qfx[] = array(
                            'main_title'=>'test',//$heading[1]->innertext,
                            'mov_details' =>$movie_info
                        );


                    unset($movie_info);

          }

        }

    print_r($qfx)

从上面我能够打印

3D:Star Trek Beyond
电影2

其他一些

但无法打印主标题现在显示即将推出即(h4 class =&#34;标题&#34;)请帮助

1 个答案:

答案 0 :(得分:0)

简单的HTML Dom不完全支持xpath难以找到兄弟元素。如果将DomDocument与Xpath一起使用,代码将更容易

$dom = new DomDocument;
$dom->loadHTML($str);
$xpath = new DomXpath($dom);

foreach($xpath->query('//div[@class="content"]/h4[@class="title"]') as $title) {
   echo $title->nodeValue . "\n";
   foreach($xpath->query('./following-sibling::div[@class="movies"]/div[@class="movie"]/h4[@class="movie-title"]',$title) as $movieTitle) {
      echo $movieTitle->nodeValue . "\n";
   }
}

<强> demo