使用 Xpath 将 href 链接替换为来自同一父节点的字符串

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,因为 XPath 开头的 / 总是引用根文档;使用 ./ 代替。在这种情况下 spandiv 的直接子代,因此您也不需要 // :

$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);