使用PHP DOMDocument更改标记属性值

时间:2022-11-27 17:10:04

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!

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

2 个解决方案

#1


26  

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

#2


5  

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

#1


26  

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

#2


5  

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