4

I have image in html. I parse it to 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 works fine line 3 gets image. line 6 understands that there is no "a" tag above this "img" tag, and line 8 must print out my initial image. But the thing is I only see "3" without image tag and etc...

I did inspect element and nothing is there. just "3" is coming out. Why I cannot print out image ?

James P.
  • 19,313
  • 27
  • 97
  • 155
David
  • 4,332
  • 13
  • 54
  • 93
  • possible duplicate of [PHP + DOMDocument: outerHTML for element?](http://stackoverflow.com/questions/5404941/php-domdocument-outerhtml-for-element) – Tomalak Jun 12 '11 at 10:47

1 Answers1

7

You could use:

DOMDocument::saveXML($img);

From PHP Documetation's 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're using PHP 5.3.6 you could use (from How to return outer html of DOMDocument?)

$doc->saveHtml($img);

Note the caveat mentioned in the linked-to question:

(...) use saveXml(), but that would create XML compliant markup. In the case of an <a>(<img>) element, that shouldn't be an issue though.

Community
  • 1
  • 1
Michael Robinson
  • 29,278
  • 12
  • 104
  • 130
  • most probably you want me to get source from that image tag, but what I want is to get back the whole "img" tags html. THat's why I'm trying to use ->nodeValue but nothing happens – David Jun 12 '11 at 10:45
  • @ Michael Sorry i'm a noobie in such questions, can you modify my example so the image will print out ? – David Jun 12 '11 at 10:52