需要有关使用PHP DOMDocument附加HTML图像的帮助

I am trying to append <img src="" alt="" > inside <body></body> using PHP DOMDocument.

Here is the code:

$testcode ='<!DOCTYPE html><html><head><title></title></head><body></body></html>';
$dom = new DOMDocument;

$dom->loadHTML($testcode);


$img_tag = $dom->createDocumentFragment();
$img_tag->appendXML('<img src="http://www.somesite.com/" alt="" >');
$body = $dom->getElementsByTagName('body');
foreach($body as $node) {
    $node->appendChild($img_tag);
}
echo $dom->saveHTML();

I was getting this error:

Message: DOMNode::appendChild(): Document Fragment is empty

But after few experiment I figured out that it was expecting closing tag. So this code worked fine:

<img src="http://www.somesite.com/" alt="" ></img>

The final appended tag looks fine. It removes the closing tag automatically.

<img src="http://www.somesite.com/" alt="" >

QUESTION: Why we have to use closing tag for this? Its not so obvious.

ANOTHER PROBLEM: Adding URL parameters triggers the same error mentioned above.

<img src="http://www.somesite.com/?v=1&param=4" alt="" >

Again after few trials, when URL was encoded its worked fine. Once again its not so obvious.

QUESTION: How can I append the image tag in simple way without doing the things I did above.

Actually I am writing a mail application where I just wanted to insert the google analytics email open tracking code at the end. Something like:

<img src="http://www.google-analytics.com/collect?v=1&t=event" alt="" >

The problem with encoded url is that its not tracking anything.

Thanks in advance!

Two things to fix:

  1. the function you are calling is appendXML. By definition, it expects XML, which is slightly different from HTML. In XML, all tags must be closed, so </img> is required to close <img>. <img src="http://www.somesite.com/" alt="" /> should also work (self-closing tag).

  2. Using the ampersand (&) unencoded is illegal in an HTML document. It should be &amp;. To convert the URL to the correct encoding, try the following:

    '<img src="' . htmlentities("http://www.somesite.com/?v=1&param=4") . " alt="" ></img>'

That will become '<img src="http://www.somesite.com/?v=1&amp;param=4" alt=""></img>'.