Print html content from a dome using nodeValue

I have an image in html. I parse it into a DOMDocument and start working with it ...

$doc = new DOMDocument(); $doc->loadHTML($article_header); $imgs = $doc->getElementsByTagName('img'); foreach ($imgs as $img) { $container = $img->parentNode; if ($container->tagName != "a") { $image_inside=utf8_decode($img->nodeValue); echo "3".$image_inside; die; } } 

This code runs thin line 3 gets the image. line 6 understands that there is no "a" tag above this "img" tag, and line 8 should print my initial image. But I see only "3" without an image tag, etc ....

I checked the item and there was nothing. only 3 comes out. Why can't I print the image?

+4
source share
1 answer

You can use:

 DOMDocument::saveXML($img); 

From PHP Documetation saveXML () .

 $doc = new DOMDocument(); $doc->loadHTML($article_header); $imgs = $doc->getElementsByTagName('img'); foreach ($imgs as $img) { $container = $img->parentNode; if ($container->tagName != "a") { echo utf8_decode($doc->saveXML($img)); die; } } 

If you are using PHP 5.3.6, you can use (from how to return an external html DOMDocument? )

 $doc->saveHtml($img); 

Note the caveat mentioned in the related question:

(...) use saveXml (), but this will create XML compatible markup. in the case of the <a>(<img>) element, which shouldn't be a problem though.

+6
source

All Articles