PHP SimpleXMLElement:我可以使用saveXML()获取innertext,还是使用(string)获取outerHTML?

时间:2017-07-15 21:37:42

标签: php xpath simplexml

我有一个应用程序,用户编写XPath查询以用作给定文档的源数据。有时它们只需要元素的内容,有时它们需要整个元素本身。根据我的理解,他们应该能够在查询结束时指定text()或node()来选择哪种行为。

但似乎我从SimpleXMLElement中获取字符串的方式决定了行为,无论查询如何。

当我将查询转换为(字符串)时,它总是只返回内部XML。

(string) $xml->xpath('//document/head/Keywords')[0] === 
(string) $xml->xpath('//document/head/Keywords/node()')[0] === 
(string) $xml->xpath('//document/head/Keywords/text()')[0] === 
'17';

如果我使用 - > saveXML(),它总是返回整个标记。

$xml->xpath('//document/head/Keywords')[0]->asXML() === 
$xml->xpath('//document/head/Keywords/node()')[0]->asXML() === 
$xml->xpath('//document/head/Keywords/text()')[0]->asXML() === 
'<Keywords topic="611x27keqj">17</Keywords>';

是否有一种方法可以获取字符串,这允许我的用户将内部和外部XML指定为其XPath查询的一部分?

1 个答案:

答案 0 :(得分:0)

The SimpleXML xpath() method always returns SimpleXMLElement objects representing either an element or an attribute, never text. The methods you show in the question are the correct way to use that object to get text content or full XML.

If you want richer (but less simple) XPath functionality, you will have to use the DOM, and specifically the DOMXPath class. Note that you can freely mix SimpleXML and DOM using simplexml_import_dom and dom_import_simplexml; the internal representation is the same, so you can switch between the two "wrappers" with minimal cost.