繁体   English   中英

xPath从表中获取值

[英]xPath to get values from table

我刚刚开始使用XPath,并且在摆弄如何正确遍历表元素以在tr中找到td值。 我试图只回显该节点的同级值。 我的桌子,例如:

<table class="123">
    <tbody>
        <tr>
            <td id="myYear">Year</td>
            <td>2001</td>
            <td>2002</td>
            <td>2003</td>
        </tr> 
        <tr>
            <td id="myScores">Scores</td>
            <td>82</td>
            <td>87</td>
            <td>94</td>
        </tr> 
    </tbody>
</table>

我的PHP代码如下:

$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;       
$dom->loadHTML($content);
$xpath = new DOMXpath($dom);

$myYear = $xpath->query('//table[@class="123"]/tbody/tr/td[@id="myYear"]');

foreach ($myYear as $year) {
    echo $year->nodeValue; //returns Year
    echo "<br>";

    $siblings = $year->nextSibling;

    foreach ($siblings as $value) {
        echo $value->nodeValue;
    }
} 

在上面的示例中,输出为“ Year”,但是对于“ myScores”的三个同级值(例如82,87,94),我没有任何输出。

感谢您的任何建议。

一些自学正在进行中! 我只是像这样使用跟随兄弟:

$myYear = $xpath->query('//table[@class="123"]/tbody/tr/td[@id="myYear"]/following-sibling::*');

foreach ($myYear as $year) {
    echo $year->nodeValue; //returns Year
    echo "<br>";
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM