Change tag attribute value with PHP DOMDocument
27,440
Solution 1
$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;
}
Solution 2
$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/');
Related videos on Youtube
Author by
apparatix
Updated on July 09, 2020Comments
-
apparatix almost 4 years
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!
-
ebohlman almost 12 yearsUpvoted because you included a type check, but please remember that in C-like languages it's a good idea to always enclose the body of a conditional or loop in curly braces, even if it's only one statement (since if you later add another statement and forget to add braces it will look like it's part of the body when it really isn't; this can cause really hard-to-find bugs).
-
Charles Sprayberry about 10 yearsThe type check is actually fairly useless here;
DOMDocument::getElementsByTagName
always returns aDOMNodeList
so theif
block will always be run. -
billybadass over 3 yearsI was not saving it. Thanks for the tip. Let's hope the library will be working in php 8.
-
AymDev about 3 yearsNote that
$item
is of type DOMElement. You won't get autocompletion in your IDE by following the documentation and typehintingDOMNode
.