doumangzhen7204 2012-07-15 19:12
浏览 44
已采纳

相对xpath php

I'm parsing html that looks like this:

  <table class="linesTbl">
        <tr class="linesHeader">
            <td><h3>EventName</h3></td>
        </tr><tr class="linesColumns">
            <td>Date</td><td class="contestLine">Description</td>
        </tr><tr class="linesAlt1">
            <td>Time</td><td>X1</td><td>Price1</td>
        </tr><tr class="linesAlt1">
            <td>&nbsp;</td><td>X2</td><td>Price2</td></tr>
</table>

There are multiple tables like this so I'm trying to loop through them and grab all of the data. I'm not sure how xpath handles queries in php. Currently I'm just trying to extract the EventName from each table.

$doc = new DOMDocument();
@$doc->loadHTML($html);
$xpath = new DOMXPath($doc);

foreach ($xpath->query("//table[@class = 'linesTbl']") as $tableNode){

  $headerTag = $xpath->query(".//h3", $tableNode);
  echo $headerTag->nodeValue;

}

For the $headerTag query I also tried query("./tr/td/h3", $tableNode). How do I go about doing this relative query?

  • 写回答

2条回答 默认 最新

  • doubipeng1336 2012-07-15 19:17
    关注

    Your xpath expression is relative already:

    $headerTag = $xpath->query(".//h3", $tableNode);
                                ^       ^^^^^^^^^^
                                |    relative-to node
                           relative path
    

    However, this returns a nodelist, not a single node, so if you do:

    echo $headerTag->item(0)->nodeValue;
                   ^^^^^^^^^
    

    You can access the element you want, see the output:

    EventName
    

    I hope this is helpful.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器