PHP DOMDocument用HTML字符串替换DOMElement小孩 [英] PHP DOMDocument replace DOMElement child with HTML string

查看:337
本文介绍了PHP DOMDocument用HTML字符串替换DOMElement小孩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用PHP我试图从WYSIWYG编辑器中传递一个HTML字符串,并用新的HTML替换预加载的HTML文档中元素的子元素。

Using PHP I'm attempting to take an HTML string passed from a WYSIWYG editor and replace the children of an element inside of a preloaded HTML document with the new HTML.

到目前为止,我正在加载标识要由ID更改的元素的文档,但将HTML转换为可放置在DOMElement内的东西的过程不在我身上。

So far I'm loading the document identifying the element I want to change by ID but the process to convert an HTML to something that can be placed inside a DOMElement is eluding me.

libxml_use_internal_errors(true);

$doc = new DOMDocument();
$doc->loadHTML($html);

$element = $doc->getElementById($item_id);
if(isset($element)){
    //Remove the old children from the element
    while($element->childNodes->length){
        $element->removeChild($element->firstChild);
    }

    //Need to build the new children from $html_string and append to $element
}


推荐答案

如果HTML字符串可以解析为XML,则可以这样做(清除所有子节点的元素后):



If the HTML string can be parsed as XML, you can do this (after clearing the element of all child nodes):

$fragment = $doc->createDocumentFragment();
$fragment->appendXML($html_string);
$element->appendChild($fragment);

如果$ html_string无法解析为XML,它将失败。如果是这样,你必须使用不太严格的loadHTML(),但它会添加元素周围的片段,你必须剥离。

If $html_string cannot be parsed as XML, it will fail. If it does, you’ll have to use loadHTML(), which is less strict — but it will add elements around the fragment which you will have to strip.

不同PHP,Javascript有innerHTML属性,可以很容易地做到这一点。我需要像项目这样的东西,所以我扩展了PHP的DOMElement,以包含类似Javascript的innerHTML访问。

Unlike PHP, Javascript has the innerHTML property which allows you to do this very easily. I needed something like it for a project so I extended PHP’s DOMElement to include Javascript-like innerHTML access.

使用它,您可以访问innerHTML属性并更改它,就像您一样将在Javascript中:

With it you can access the innerHTML property and change it just as you would in Javascript:

echo $element->innerHTML;
$elem->innerHTML = '<a href="http://example.org">example</a>';






资料来源: http://www.keyvan.net/2012/11/php- domdocument-replace-domelement-child-with-html-string /

这篇关于PHP DOMDocument用HTML字符串替换DOMElement小孩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆