Search code examples
phpxmlxpathsimplexml

PHP XML: Getting text of a node and its children


I know that this questions has been asked before, but I cannot make it work. I'm using simplexml and xpath in a PHP file. I need to get text from a node including the text in its child nodes. So, the results should be:

Mr.Smith bought a white convertible car.

Here is the 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>

The php that's not working is:

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

Please help!


Solution

  • To get the node value with all its child elements, you can use 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