PHP SimpleXML获取innerXML

Bar*_*lom 8 php innerxml simplexml

我需要answer在这一点XML中获取HTML内容:

<qa>
 <question>Who are you?</question>
 <answer>Who who, <strong>who who</strong>, <em>me</em></answer>
</qa>
Run Code Online (Sandbox Code Playgroud)

所以我希望得到一个字符串"Who who,<strong>谁是</ strong>,<em> me </ em>".

如果我有answera SimpleXMLElement,我可以打电话asXML()来"<answer>谁是谁,<strong>谁</ strong>,<em>我</ em> </ answer>",但是如何获得内部XML没有元素本身缠绕的元素?

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

小智 13

function SimpleXMLElement_innerXML($xml)
  {
    $innerXML= '';
    foreach (dom_import_simplexml($xml)->childNodes as $child)
    {
        $innerXML .= $child->ownerDocument->saveXML( $child );
    }
    return $innerXML;
  };
Run Code Online (Sandbox Code Playgroud)


小智 6

这有效(虽然看起来真的很蹩脚):

echo (string)$qa->answer;
Run Code Online (Sandbox Code Playgroud)


Jos*_*vis 5

据我所知,没有内置的方法来实现这一点.我建议尝试使用SimpleDOM,这是一个扩展SimpleXMLElement的PHP类,它为大多数常见问题提供了方便的方法.

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();
Run Code Online (Sandbox Code Playgroud)

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