dougou5852 2014-11-23 04:40
浏览 73
已采纳

PHP - 在找到元素后从元素中获取链接

I have the following code....

<div class="outer">
<div>
<h1>Christmas</h1>
 <ul>
  <li>Holiday</li>
  <li>Fun</li>
  <li>Joy</li>
 </ul>
<h1>4th July</h1>
 <ul>
  <li>Fireworks</li>
  <li>Happy</li>
  <li>Spectral</li>
 </ul>
</div>
</div>
<div class="outer">
<div>
<h1>Christmas2</h1>
 <ul>
  <li>Holiday</li>
  <li>Fun</li>
  <li>Joy</li>
 </ul>
<h1>4th July</h1>
 <ul>
  <li>Fireworks2</li>
  <li>Happy</li>
  <li>Spectral</li>
 </ul>
</div>
</div>

I already know that I can find the DIV and then look inside the DIV for the elements etc by doing...

$doc->loadHTML($output);    //$output being the text above
$xpath = new DOMXpath($doc);
$elements = $xpath->query('//div[@class="outer"]');  //Check outer

I know this above 3 lines will get the elements from within the DIV listed, but what I really want to be able to do is get the text of the [H1], then display the [li] values next to each H1..

the output i'm looking for is...

Christmas - Holiday, Fun, Joy
4th July - Fireworks, Happy, Spectral
Christmas2 - Holiday, Fun, Joy
4th July2 - Fireworks, Happy, Spectral
  • 写回答

2条回答

  • douyueju2912 2014-11-23 05:01
    关注

    Yes you can continue to use xpath to traverse the elements on the header and get its following sibling, the list. Example:

    $doc = new DOMDocument();
    $doc->loadHTML($output);
    $xpath = new DOMXpath($doc);
    $elements = $xpath->query('//div[@class="outer"]/div');
    if($elements->length > 0) {
        foreach($elements as $div) {
            foreach ($xpath->query('./h1', $div) as $e) {
                $header = $e->nodeValue;
                $list = array();
                foreach ($xpath->query('./following-sibling::ul/li', $e) as $li) {
    
                    $list[] = $li->nodeValue;
                }
    
                echo $header . ' - ' . implode(', ', $list) . '<br/>';
            }
            echo '<hr/>';
        }   
    }
    

    Sample Output

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧