doucang2831 2016-03-13 15:38
浏览 15
已采纳

简单的HTML dom - 在另一个上面找到一个元素

I'm using PHP Simple DOM Parser (http://simplehtmldom.sourceforge.net/),

So far I've managed to do what I want with it, however I'm attempting to get some text of the first element with a certain class above another.

My issue is that the divs aren't nested in the area I need to get the information from. Like so:

<div class="day">Sunday<div>
<div class="game">...</div>
<div class="game">...</div>
...
<div class="day">Monday<div>
<div class="game">...</div>
<div class="game">...</div>
...

Each game has a title, time, channels.. So whilst I'm gathering all of that in to my array I want to be able to find the first class="day" in order to add it to my array.

$html->find('h2.time_head') is how I'm currently getting the day heads, but I'm not sure how I can match it up to my games, as I'm getting them foreach($html->find('div.blockfix') as $div) like so.

Any help is appreciated.

  • 写回答

1条回答 默认 最新

  • dqyy38265 2016-03-13 16:24
    关注

    If above HTML sample is the content of <div class="blockfix">, you can retrieve corresponding day in this way:

    foreach( $html->find('div.blockfix') as $block )
    {
        foreach( $block->find('div.game') as $div )
        {
            $day = $div;
            while( $day = $day->prev_sibling()  )
            {
                if( $day->class == 'day' ) break;
            }
            if( $day ) echo $day->__toString();
            else       echo 'no day found';
        }
    }
    

    I leave your basic foreach because I don't know if you do some other stuffs, but if you prefer you can perform a unique foreach:

    foreach( $html->find('div.blockfix div.game') as $div )
    

    The core of code is the use of ->prev_sibling(): we check each previous sibling of current “game” <div> until we found “day” class.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应