PHP XML: 获取节点及其子节点的文本

PHP XML: Getting text of a node and its children

我知道以前有人问过这个问题,但我做不到。我在 PHP 文件中使用简单 xml 和 xpath。我需要从一个节点获取文本,包括其子节点中的文本。所以,结果应该是:

Mr.Smith bought a white convertible car.

这是xml:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="test9.xsl"?>
<items>
    <item>
        <description>
            <name>Mr.Smith bought a <car>white</car> <car>convertible</car> car.</name>
        </description>
    </item>
</items>

无效的 php 是:

$text = $xml->xpath('//items/item/description/name');
    foreach($text as &$value) {
        echo $value;
}

请帮忙!

要获取节点值及其所有子元素,可以使用DOMDocument, with C14n():

<?php
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="test9.xsl"?>
<items>
    <item>
        <description>
            <name>Mr.Smith bought a <car>white</car> <car>convertible</car> car.</name>
        </description>
    </item>
</items>
XML;
$doc = new DOMDocument;
$doc->loadXML($xml);
$x = new DOMXpath($doc);
$text = $x->query('//items/item/description/name');
echo $text[0]->C14n(); // Mr.Smith bought a white convertible car.

Demo