[英]Using Xpath to replace href links with a string from the same parent node
我似乎无法获得正确的表达式来修改查询结果的 href 链接,其中的字符串(将设置为新 url)取自另一个查询但位于同一父节点上。 考虑这个结构:
<table>
<tr>
<td>
<div class=items>
<span class="working-link">link-1</span>
<a href="broken-link">Item 1</a>
</div>
</td>
<td>
<div class=items>
<span class="working-link">link-2</span>
<a href="broken-link">Item 2</a>
</div>
</td>
</tr>
<table>
到目前为止,这是我想出的,但没有结果:
$xpath = new DomXPath($doc);
$nodeList = $xpath->query("//div[@class='items']");
foreach( $nodeList as $result) {
$newLink = $xpath->query("//span[@class='working-link']",$result);
foreach($result->getElementsByTagName('a') as $link) {
$link->setAttribute('href', $newLink);
}
echo $doc->saveHTML($result);
}
基本上,您永远不应该在 XPath 的开头以/
as /
开始相对 XPath 始终引用根文档; 使用./
代替。 在这种情况下, span
是div
直接子级,因此您也不需要//
:
$newLink = $xpath->query("./span[@class='working-link']",$result);
或者完全删除./
:
$newLink = $xpath->query("span[@class='working-link']",$result);
解决了! 这里的问题是对错误的数据类型使用函数。 它应该是
$newLink = $xpath->query("span[@class='working-link']",$result)[0];
表示它是数组的索引。 之后将其转换为字符串以供 setAttribute 使用
$link->setAttribute('href', $newLink->textContent);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.