本文介绍了PHP SimpleXML获取innerXML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取XML的answer的HTML内容:

I need to get the HTML contents of answer in this bit of XML:

<qa>
 <question>Who are you?</question>
 <answer>Who who, <strong>who who</strong>, <em>me</em></answer>
</qa>

所以我想获取字符串谁,谁,谁,谁,谁,谁,谁,谁,我,他们,我,他们".

So I want to get the string "Who who, <strong>who who</strong>, <em>me</em>".

如果我将answer作为SimpleXMLElement,则可以调用asXML()以获得< answer>谁,< strong>谁,</strong>,< em>我</em></answer>",但是如何获取元素的内部XML而又不将元素本身包裹起来呢?

If I have the answer as a SimpleXMLElement, I can call asXML() to get "<answer>Who who, <strong>who who</strong>, <em>me</em></answer>", but how to get the inner XML of an element without the element itself wrapped around it?

我更喜欢不涉及字符串函数的方法,但是如果那是唯一的方法,那就这样吧.

I'd prefer ways that don't involve string functions, but if that's the only way, so be it.

推荐答案

据我所知,没有内置的方法可以做到这一点.我建议尝试 SimpleDOM ,这是一个扩展SimpleXMLElement的PHP类,它为大多数情况提供了便利的方法常见问题.

To the best of my knowledge, there is not built-in way to get that. I'd recommend trying SimpleDOM, which is a PHP class extending SimpleXMLElement that offers convenience methods for most of the common problems.

include 'SimpleDOM.php';

$qa = simpledom_load_string(
    '<qa>
       <question>Who are you?</question>
       <answer>Who who, <strong>who who</strong>, <em>me</em></answer>
    </qa>'
);
echo $qa->answer->innerXML();

否则,我看到了两种方法.首先是将您的SimpleXMLElement转换为DOMNode,然后在其childNodes上循环以构建XML.另一种方法是调用asXML()然后使用字符串函数删除根节点.但是请注意,asXML()有时可能会返回标记,该标记实际上在调用它的节点的 之外,例如XML prolog或Processing Instructions.

Otherwise, I see two ways of doing that. The first would be to convert your SimpleXMLElement to a DOMNode then loop over its childNodes to build the XML. The other would be to call asXML() then use string functions to remove the root node. Attention though, asXML() may sometimes return markup that is actually outside of the node it was called from, such as XML prolog or Processing Instructions.

这篇关于PHP SimpleXML获取innerXML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 01:00