Php xPath从表中获取值
我刚刚开始使用XPath,正在研究如何正确遍历表元素以在tr中找到td值。我试图只回显节点的同级值。例如,我的表格:Php xPath从表中获取值,php,xpath,domdocument,Php,Xpath,Domdocument,我刚刚开始使用XPath,正在研究如何正确遍历表元素以在tr中找到td值。我试图只回显节点的同级值。例如,我的表格: <table class="123"> <tbody> <tr> <td id="myYear">Year</td> <td>2001</td> <td>2002</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>
年
2001
2002
2003
分数
82
87
94
我的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;
}
}
$dom=新的DOMDocument;
$dom->preserveWhiteSpace=false;
$dom->loadHTML($content);
$xpath=newdomxpath($dom);
$myYear=$xpath->query('//table[@class=“123”]/tbody/tr/td[@id=“myYear”]”);
foreach($myYear作为$year){
echo$year->nodeValue;//返回年份
回声“
”;
$SIBLINES=$year->nextSibling;
foreach(兄弟姐妹作为$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>";
}
$myYear=$xpath->query('//table[@class=“123”]/tbody/tr/td[@id=“myYear”]/以下同级::*);
foreach($myYear作为$year){
echo$year->nodeValue;//返回年份
回声“
”;
}