Getting Values from Simple XML

I got stuck trying to get contents of a node from an XML document without retriving the entire object for that node.


error_reporting(E_ALL); $xmlstr = <<<

<title>PHP: Behind the Parser</title>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
<name>Mr. Coder</name>
<actor>El ActÓr</actor>
So, this language. It’s like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
<rating type=”thumbs”>7</rating>
<rating type=”stars”>5</rating>



$xml = simplexml_load_string($xmlstr);

While doing this

echo $xml->movie[0]->title;

echos the correct value, if you were to run print_r on it you’d see that it is an object of type SimpleXMLElement. So how to get just the title as a string and not the object so i could assign the value to a variable maybe do a few calculations you know… a little coding..?!

This took some time for me 🙂 i was having an off day…

$title = (string) $xml->movie[0]->title;

$price = (int) $xml->movie[0]->ticketPrice;

The casting of the node returns the value stored. Not the object, so now i can use the value where ever i want.

It certainly makes it clearer when debugging and allows you to run code like is_numeric($xml->movie[0]->ticketPrice) which was failling for me…

so casting is the order of the day today…

Have a good weekend.