Search code examples
phpdomdomdocumentnodevalue

php replace link value


$links = $li->getElementsByTagName('a');

foreach ($links as $link)
{
$link_text = $link->nodeValue;
$image = $dom->createElement('img');
$image->setAttribute('src', 'some target');
$image->setAttribute('alt', $link_text);

$link->nodeValue($image); // doesnt work
}

How do I replace link's nodevalue with the new one? (using domdocument)

There is actually one link inside li, but I'm not sure how to get it without foreach.


Solution

  • You could try this (with $doc being your DOMDocument).

    // saveHTML returns the node as a string of HTML.
    $link->nodeValue = $doc->saveHTML($image);
    

    Or, more appropriately, you could add the image as a child node:

    // name should be self-documenting.
    $link->appendChild($image);
    

    Also, if you only have one, you could simply use the item method and avoid the foreach:

    $link = $li->getElementsByTagName('a')->item(0);