首页 文章

PHP XPath表元素消失

提问于
浏览
0

我刚刚了解了XPath,我只想从表中的某些列读取数据 .

我当前的代码如下所示:

<?php

$file_contents = file_get_contents('test.html');

$dom_document = new DOMDocument();

$dom_document->loadHTML($file_contents);

//use DOMXpath to navigate the html with the DOM
$dom_xpath = new DOMXpath($dom_document);

$elements = $dom_xpath->query("//tr[@class='rowstyle']");

if (!is_null($elements)) {
    foreach ($elements as $element) 
    {
        echo $element->nodeValue . '
'; } } else { echo 'none'; } ?>

也是查询中的变体,因为通过我的研究我看到了很多关于嵌套表元素的问题,但它产生了相同的结果:

$elements = $dom_xpath->query("//table[@class='tablestyle']/tbody/tr[@class='rowstyle']");

它确实抓取了一行数据,但它将成为一个字符串,将所有单元格组合成一个字符串并使标记消失 .

我真正想要做的是分离这些单元格并获取特定的行号 .

我也很好奇如何找出我的XPath版本...我的PHP版本是5.3.5

1 回答

  • 1

    它没有组合这些单元格...你输出 nodeValue ,在这种情况下表现得像 innerHTML . 如果你想处理单元格本身,可以使用 childNodes 或使用行作为上下文的xpah查询,然后遍历单元格 .

    例:

    $dom_xpath = new DOMXpath($dom_document);
    
    $elements = $dom_xpath->query("//tr[@class='rowstyle']");
    foreach ($elements as $element) 
    {
      foreach($element->childNodes as $cell) {
         echo $cell->nodeValue . '
    '; } }

相关问题