开发者

removeChild with PHP DOM doesn't work

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开发者_如何学Go 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!


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 = '#';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜