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

时间:2017-10-17 16:03:28

标签: php xml xpath simplexml

我知道之前已经提出过这个问题,但我无法让它发挥作用。我在PHP文件中使用simplexml和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;
}

请帮忙!

1 个答案:

答案 0 :(得分:0)

要获取包含其所有子元素的节点值,您可以DOMDocument使用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