【发布时间】:2021-06-11 14:21:56
【问题描述】:
我使用 PHP foreach 循环遍历一组超链接。 如果满足条件,我想更改超链接的href。如果没有,循环可以继续。 我可以使用 echo $node->getAttribute( 'href' ); 回显当前的 href 但是我无法使用以下方法更改它: $node->setAttribute('href', "https://www.website2.com");
我在这里遗漏了一些东西,但我已经坚持了一段时间。
完整代码:
$dom = new DOMDocument;
$dom->loadHTML($homepage);
foreach ($dom->getElementsByTagName('a') as $node) {
if ($node->getAttribute( 'href' ) == "https://www.website1.com" ) {
echo $node->getAttribute( 'href' );
$node->setAttribute('href', "https://www.website2.com");
}
}
$html = $dom->saveHTML();
【问题讨论】:
-
您是否真的在脚本末尾保存了文档?
-
不,我不这么认为
-
如果您不保存,更改将不会是永久性的。这取决于您如何使用上述内容。
-
我应该添加什么来保存文档?也许就这么简单:)
-
$html = $dom->saveHTML();
标签: php domdocument getelementsbytagname setattribute getattribute