如何将一个节点的xml内容作为字符串获取? [英] How to get the xml content of a node as a string?

查看:108
本文介绍了如何将一个节点的xml内容作为字符串获取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用PHP的DOM函数,如何将DOM节点的内容转换为字符串?

Using PHP's DOM functions, how do you convert a DOM Node's contents into a string?

<foo>
    Blah blah <bar baz="1">bah</bar> blah blah
</foo>

给定 foo 作为当前上下文节点,你如何获得'Blah blah< bar baz =1> bah< / bar> blah blah'作为一个字符串?使用 $ node-> textContent $ node-> nodeValue 只返回文本节点,而不是< bar baz =1> 位。

Given foo as the current context node, how do you get 'Blah blah <bar baz="1">bah</bar> blah blah' as a string? Using $node->textContent or $node->nodeValue just returns the text nodes, not the <bar baz="1"> bits.

基本上,相当于Javascript的 innerHTML 属性...

Basically, the equivalent of Javascript's innerHTML property...

推荐答案

您可以从< foo> 节点创建一个新的DOMDocument,并将其解析为XML或HTML:

You can create a new DOMDocument from the <foo> node and parse it as XML or HTML:

function getInnerHTML($node) {
    $tmpDoc = new DOMDocument('1.0');
    $block = $tmpDoc->importNode($node->cloneNode(true),true);
    $tmpDoc->appendChild($block);
    $outer = $tmpDoc->saveHTML();
    //this will remove the outer tags
    return substr($outer,strpos($outer,'>')+1,-(strlen($node->nodeName)+4)); 
}

这篇关于如何将一个节点的xml内容作为字符串获取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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