使用 PHP DOMDocument 更改标签属性值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11387748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change tag attribute value with PHP DOMDocument
提问by apparatix
I want to change the value of the attribute of a tag with PHP DOMDocument.
我想用 PHP DOMDocument 更改标签的属性值。
For example, say we have this line of HTML:
例如,假设我们有这行 HTML:
<a href="http://foo.bar/">Click here</a>
I load the above code in PHP as follows:
我在PHP中加载上面的代码如下:
$dom = new domDocument;
$dom->loadHTML('<a href="http://foo.bar/">Click here</a>');
I want to change the "href" value to "http://google.com/" using the DOMDocument extension of PHP. Is this possible?
我想使用 PHP 的 DOMDocument 扩展将“href”值更改为“http://google.com/”。这可能吗?
Thanks for the help as always!
感谢您一如既往的帮助!
回答by phirschybar
$dom = new DOMDocument();
$dom->loadHTML('<a href="http://foo.bar/">Click here</a>');
foreach ($dom->getElementsByTagName('a') as $item) {
$item->setAttribute('href', 'http://google.com/');
echo $dom->saveHTML();
exit;
}
回答by iDexter
$dom = new domDocument;
$dom->loadHTML('<a href="http://foo.bar/">Click here</a>');
$elements = $dom->getElementsByTagName( 'a' );
if($elements instanceof DOMNodeList)
foreach($elements as $domElement)
$domElement->setAttribute('href', 'http://www.google.com/');

