Change tag attribute value with PHP DOMDocument

apparatix picture apparatix · Jul 9, 2012 · Viewed 24.8k times · Source

I want to change the value of the attribute of a tag with PHP DOMDocument.

For example, say we have this line of HTML:

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

I load the above code in PHP as follows:

$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?

Thanks for the help as always!

Answer

phirschybar picture phirschybar · Jul 9, 2012
$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;
}