Simplexml_load_file () does not receive node content

I cannot get the contents and attributes of an XML node at the same time as the SimpleXML library:

I have the following XML and want to get the attribute content@nameand node content:

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

Simplexml_load_string () method

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, the content of the contentnode is present but the attributes are missing. How can I get the content and attributes?

Thank!

+4
source share
3 answers
$x = simplexml_load_string('<page id="id1"><content name="abc">def</content></page>');

To get the node attributes:

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

To get the contents of contentnode:

$c = $x->content;

Interestingly, $ c can be used as a string and as an object, i.e.

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

. print_r() XML .

$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

In simplexml, accessing elements returns SimpleXMLElement objects. You can view the contents of these objects with 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 using the 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 extract content (for example, elements and attributes), but also add and delete them. You can also use Xpath to move values ​​into a complex XML tree. You just need to go through the class of the SimpleXMLElement class here .

+1
source

Source: https://habr.com/ru/post/1584040/


All Articles