28

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!

apparatix
  • 1,492
  • 7
  • 22
  • 37

2 Answers2

48
$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;
}
phirschybar
  • 8,357
  • 12
  • 50
  • 66
  • I was not saving it. Thanks for the tip. Let's hope the library will be working in php 8. – billybadass Nov 12 '20 at 11:17
  • 1
    Note that `$item` is of type [DOMElement](https://www.php.net/manual/en/class.domelement.php). You won't get autocompletion in your IDE by following the documentation and typehinting `DOMNode`. – AymDev May 10 '21 at 12:13
10
$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/');
Anton Kucherov
  • 307
  • 1
  • 6
  • 2
    Upvoted 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). – ebohlman Jul 09 '12 at 03:52
  • 5
    The type check is actually fairly useless here; `DOMDocument::getElementsByTagName` always returns a `DOMNodeList` so the `if` block will always be run. – Charles Sprayberry Mar 17 '14 at 15:17