Question

I have the following code:

$doc = new DOMDocument();
$doc->loadHTML($quiz['value']);
$imageElement = $doc->getElementsByTagName('img')->item(0);
}
if(is_object($imageElement)){ 
    $image = $imageElement->getAttribute('src');
    $imageElement->parentNode->removeChild($imageElement); 
}else{ 
    $image = '#'; 
}
$quiz['value'] = $doc->saveHTML();

However, I get the following error: Fatal error: Call to a member function removeChild() on a non-object.

The loaded dom string may or may not contain an img element. Does anybody know what I'm doing wrong here? Any help is greatly appreciated!

Was it helpful?

Solution

is_object() isn't a good test for this, as ->item() will return an object no matter what. It just won't be a DOMNode if there isn't an actual matching item in the DOMNodeList that the getElementsByTagName returns.

A better method would be:

$images = $doc->getElementsByTagName('img');
if ($images->length > 0) {
   $imgnode = $images->item(0);
   $image = $imgnode->getAttribute('src');
   $imgnode->parentNode->removeChild($imgnode); 
} else {
   $image = '#';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top