doutuobao9736 2015-07-19 12:17
浏览 73
已采纳

需要有关使用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!

  • 写回答

1条回答 默认 最新

  • dousao6260 2015-07-19 13:01
    关注

    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>'.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?