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

问题描述 投票:2回答:2

我似乎无法使用从另一个查询但在同一父节点上获取的字符串(将被设置为新URL)来修改查询结果的href链接。考虑这个结构:

<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);
}
php xpath syntax domdocument
2个回答
2
投票

基本上,你永远不应该使用/启动相对XPath,因为在XPath开头的/总是引用根文档;改用./。在这种情况下,spandiv的直接孩子,所以你不需要//

$newLink = $xpath->query("./span[@class='working-link']",$result);

或者只是完全删除./

$newLink = $xpath->query("span[@class='working-link']",$result);

0
投票

解决了!这里的问题是使用错误数据类型的函数。它应该是

$newLink =  $xpath->query("span[@class='working-link']",$result)[0];

表明它是数组的索引。之后将其转换为字符串以供setAttribute使用

$link->setAttribute('href', $newLink->textContent);
© www.soinside.com 2019 - 2024. All rights reserved.