EDIT: related to PHP HTML DomDocument getElementById problems
Can't get getElementById()
to work. Document is valid, according to using W3C validator. Plus my code should work even with a little invalid HTML.
This simple code looks for an image with id="banner"
and replace it's src
attribute with another one. Works on my development machine (Windows), doesn't work on server (Ubuntu).
Any idea of how to do this without getElementById()
?
libxml_use_internal_errors(true);
// Create the DOMDocument and get the HTML content
$document = new \DOMDocument();
// Load HTML string and if it fails just return the content itself
if(false === $document->loadHTML($content)) return $content;
// Get DOMElement of the image with id="banner"
$img = $document->getElementById('banner');
// Return the content if it can't find the image
if(null === $img) return $content;
// Get image parent and remove the banner from DOM
$parent = $img->parentNode;
$parent->removeChild($img);
// Set the new src attribute
$img->setAttribute('src', 'http://mysite.come/img/myimage.png');
// Append the modified node to banner parent
$parent->appendChild($img);
return $document->saveHTML();