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 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化