这是我的XML数据:
$data = '<title>Report of the <org reg="International Foo and Bar Conference, 5th">Fifth International Foo and Bar Conference</org>, <org>Foobar Hall</org>, London, July 14 to 16, 1908.</title>';
我可以加载它:
$xml = simplexml_load_string( $data );
print_r( $xml );
返回:
SimpleXMLElement Object (
[org] => Array (
[0] => Fifth International Foo and Bar Conference
[1] => Foobar Hall ) )
但现在我可以尝试再次使用字符串:
$flat = (string) $xml;
print_r( $flat );
这就是我所看到的:
Report of the , , London, July 14 to 16, 1908.
但我宁愿这是这样的:
Report of the Fifth International Foo and Bar Conference, Foobar Hall, London, July 14 to 16, 1908.
有没有一种简单的方法可以使用PHP,而不是通过每个节点显式递归?也就是说,有没有一种方法可以简化XML并从中提取所有文本,而不管标记是什么?
解决方法:
这可以在DOM中轻松完成. DOM元素节点具有属性$textContent,它将返回其文本内容,包括所有后代文本节点.
$document = new DOMDocument();
$document->loadXml($data);
var_dump($document->documentElement->textContent);
输出:
string(99) "Report of the Fifth International Foo and Bar Conference, Foobar Hall, London, July 14 to 16, 1908."
如果您没有元素节点已经在变量中,则使用XPath会更方便.
$document = new DOMDocument();
$document->loadXml($data);
$xpath = new DOMXpath($document);
var_dump($xpath->evaluate('string(/title)'));
甚至可以将SimpleXMLElement转换为DOM元素节点.
$element = new SimpleXMLElement($data);
$node = dom_import_simplexml($element);
var_dump($node->textContent);