Search code examples
phpxmlsimplexml

simplexml_load_file() does not getting node content


I cannot get XML node contents and attributes at the same time with SimpleXML library:

I have the following XML, and want to get content@name attribute and node's contents:

<page id="id1">
    <content name="abc">def</content>
</page>

Method simplexml_load_string()

print_r(simplexml_load_string('<page id="id1"><content name="abc">def</content></page>'));

outputs this:

SimpleXMLElement Object
(
   [@attributes] => Array
        (
            [id] => id1
        )

    [content] => def
)

As you can see, contents of the content node is present, but attributes are missing. How can I receive the contents and attributes?

Thanks!


Solution

  • $x = simplexml_load_string('<page id="id1"><content name="abc">def</content></page>');
    

    To get the node's attributes:

    $attributes = $x->content->attributes(); //where content is the name of the node 
    $name = $attributes['name'];
    

    To get the content node's content:

    $c = $x->content;
    

    Interesting, that $c can be used as string and as object, i.e.

    echo $c; //prints string
    print_r($c) //prints it out as object