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!
PHP | DOMElement setAttribute() Function The DOMElement::setAttribute() function is an inbuilt function in PHP which is used to set an attribute with given name to the given value. If the attribute does not exist, it will be created.
To change the attribute value of an HTML element HTML DOM provides two methods which are getAttribute() and setAttribute(). The getAttribute() is used to extract the current value of the attribute while setAttribute() is used to alter the value of the attribute.
$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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With