Search code examples
phpxpathsimplexml

SimpleXML and xpath getting a node's value


I have the following notes.xml XML file.

<?xml version="1.0" encoding="UTF-8"?>
<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>

And this PHP script

<?php
    $xml = simplexml_load_file('notes.xml');
    $result = $xml->xpath('//to');
    print_r($result);
    echo "<br>";
    echo $result;
?> 

Then, why the output is the following? (THERE IS NOT TOVE VALUE)

Array ( [0] => SimpleXMLElement Object ( ) )
Array 

Solution

  • $result = $xml->xpath('//to');
    

    This will return you an array of SimpleXMLElement objects, since there may be more than one <to> tag in your XML. In order to extract the text, you should use

    echo (string) $result[0];
    

    Casting to a string returns the text content from the tag.

    If your XML is always that simple, you can also use

    $result = (string) $xml->to;