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.

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

报告相同问题?

悬赏问题

  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导
  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥15 基于图神经网络的COVID-19药物筛选研究
  • ¥30 软件自定义无线电该怎样使用