Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change tag attribute value with PHP DOMDocument

Tags:

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!

like image 296
apparatix Avatar asked Jul 09 '12 00:07

apparatix


People also ask

How to set attribute value in PHP?

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.

How to change attribute value in DOM?

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.


1 Answers

$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; } 
like image 182
phirschybar Avatar answered Jan 04 '23 23:01

phirschybar