我需要在文章中间插入带有div元素的图像。该页面是使用CRM中的PHP生成的。我有一个例程来计算所有段落标签的字符,并在具有第120个字符的段落之后插入HTML。我正在使用appendXML
,并且在尝试插入图像元素之前它一直有效。
当我将<img>
元素放入时,它会被剥离。我了解它正在寻找XML,但是,我关闭了我认为会有所帮助的<img>
标签。
是否有一种使用appendXML
而不剥离img元素的方法?
$mcustomHTML = "<div style="position:relative; overflow:hidden;"><a href="https://example.com/code=123456"><img src="https://s3.amazonaws.com/a.example.com/image.png" alt="No image" /></img></a></div>";
$doc = new DOMDocument();
$doc->loadHTML('<?xml encoding="utf-8" ?>' . $content);
// read all <p> tags and count the text until reach character 120
// then add the custom html into current node
$pTags = $doc->getElementsByTagName('p');
foreach($pTags as $tag) {
$characterCounter += strlen($tag->nodeValue);
if($characterCounter > 120) {
// this is the desired node, so put html code here
$template = $doc->createDocumentFragment();
$template->appendXML($mcustomHTML);
$tag->appendChild($template);
break;
}
}
return $doc->saveHTML();
答案 0 :(得分:1)
这应该为您工作。它使用一个临时DOM文档将您拥有的HTML字符串转换为可行的字符串。然后,我们将临时文档的内容导入主文档。导入后,我们可以像添加其他节点一样简单地添加它。
<?php
$mcustomHTML = '<div style="position:relative; overflow:hidden;"><a href="https://example.com/code=123456"><img src="https://s3.amazonaws.com/a.example.com/image.png" alt="No image" /></a></div>';
$customDoc = new DOMDocument();
$customDoc->loadHTML($mcustomHTML, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$doc = new DOMDocument();
$doc->loadHTML($content);
$customImport = $doc->importNode($customDoc->documentElement, true);
// read all <p> tags and count the text until reach character 120
// then add the custom html into current node
$pTags = $doc->getElementsByTagName('p');
foreach($pTags as $tag) {
$characterCounter += strlen($tag->nodeValue);
if($characterCounter > 120) {
// this is the desired node, so put html code here
$tag->appendChild($customImport);
break;
}
}
return $doc->saveHTML();