Change tag attribute value with PHP DOMDocument

attributes, dom, domdocument, php, tags

Solution

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

Problem

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!

Original source