使用PHP DOMDocument更改标记属性值


Change tag attribute value with PHP DOMDocument

我想用PHP DOMDocument更改标记的属性值。

例如,假设我们有这行HTML:

<a href="http://foo.bar/">Click here</a>

我用PHP加载上面的代码,如下所示:

$dom = new domDocument;
$dom->loadHTML('<a href="http://foo.bar/">Click here</a>');

我想将"href"值更改为http://google.com/"使用PHP的DOMDocument扩展。这可能吗?

一如既往地感谢您的帮助!

$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;
}
$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/');