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.

thus..

error_reporting(E_ALL); $xmlstr = <<<

<movies>
<movie>
<title>PHP: Behind the Parser</title>
<characters>
<character>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>El ActÓr</actor>
</character>
</characters>
<plot>
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.
</plot>
<ticketPrice>10</ticketPrice>
<views>25</views>
<rating type=”thumbs”>7</rating>
<rating type=”stars”>5</rating>
<isAdult>1</isAdult>
</movie>

</movies>

XML;

$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.