NaturalBornCamper NaturalBornCamper -4 years ago 78
PHP Question

PHP SimpleXML - can't get a single node value, am I crazy?

I simplified my php code to the minimum and still cannot get a simple xml node's value. I re-read the documentation to make sure I wasn't missing some tiny details and I just can't get it to work.

First I load this very basic XML

$xmlStrShipping = simplexml_load_string('<?xml version="1.0" encoding="utf-8" ?>
<Shipping>
<Orders>
<Order>
<number>Order number</number>
<details></details>
</Order>
</Orders>
</Shipping>');


Then I can't get the number and details nodes' value, I just keep getting a SimpleXMLElement Object:

var_dump($xmlStrShipping); // So far, so good
/* Returns:
SimpleXMLElement Object
(
[Orders] => SimpleXMLElement Object
(
[Order] => SimpleXMLElement Object
(
[number] => Order number
[details] => SimpleXMLElement Object
(
)

)

)

)
*/


.

var_dump($xmlStrShipping->Orders[0]->Order->number); // Why is this happening?
/* Returns
SimpleXMLElement Object
(
[0] => Order number
)
*/


.

var_dump($xmlStrShipping->Orders[0]->Order->number[0]); // What??
/* Returns
SimpleXMLElement Object
(
)
*/


Why can't I retrieve number?

And why is details a SimpleXMLElement Object instead of an empty string?

Answer Source

SimpleXML turns everything into SimpleXMLElement objects. Just cast it to a string (or whatever):

(string) $xmlStrShipping->Orders[0]->Order->number;

or if you invoke it in a string context it will work as well because SimpleXMLElement has the magic __toString() method implemented:

echo $xmlStrShipping->Orders[0]->Order->number;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download