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

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

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题