4
votes

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!

3
Introduction with examples on how to access elements and attributes with SimpleXML is given here in the PHP manual with great detail: Basic SimpleXML usage - you might find it informative - hakre

3 Answers

1
votes

The attributes of content are present. This is just a trick of print_r() and how it works with XML objects in memory.

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

print_r($x->content);
print_r($x->content['name']);
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [name] => abc
        )

    [0] => def
)

SimpleXMLElement Object
(
    [0] => abc
)
1
votes

In simplexml, accessing elements returns SimpleXMLElement objects. You can view the content of these objects using var_dump.

$book=simplexml_load_string('<page id="id1"><content name="abc">def</content></page>');
$content=$book->content;
var_dump($content);

You can access these objects with foreach loop.

foreach($obj as $value) {
if (is_array($value)) {
    foreach ($value as $name=>$value) {
    print $name.": ".$value."\n";}       
                        }
                else print $value;
       }

You can not only retrieve contents (such as elements and attributes) but also add and remove them. You can also use Xpath to navigate values in complex XML tree. You just need to go through the methods of SimpleXMLElement class here.

1
votes
$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