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 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么