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/');
Share:
27,440

Related videos on Youtube

apparatix
Author by

apparatix

Updated on July 09, 2020

Comments

  • apparatix
    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
    ebohlman almost 12 years
    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).
  • Charles Sprayberry
    Charles Sprayberry about 10 years
    The type check is actually fairly useless here; DOMDocument::getElementsByTagName always returns a DOMNodeList so the if block will always be run.
  • billybadass
    billybadass over 3 years
    I was not saving it. Thanks for the tip. Let's hope the library will be working in php 8.
  • AymDev
    AymDev about 3 years
    Note that $item is of type DOMElement. You won't get autocompletion in your IDE by following the documentation and typehinting DOMNode.