I have the following SimpleXMLElement Object http://pastebin.com/qEP0UUPJ
I can query it using xpath $xaugbp = $xml->xpath("/query/results/rate"); but this just narrows down the search:
I wish to access the following object:
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => XAUGBP
)
[Name] => XAU to GBP
[Rate] => 1030.5784
[Date] => 7/27/2012
[Time] => 5:55pm
[Ask] => 1027.5662
[Bid] => 1033.5896
I can get that particular object using
$ob = $xmlObject->xpath("//query/results/rate[contains(@id, 'XAUGBP')]");
I can get ‘Ask’ by using
$ob = $xmlObject->xpath("//query/results/rate[contains(@id, 'XAUGBP')]/Ask");
But how do I turn that object into a variable. e.g. so that I can do calculations on it?
Is xpath the only way of doing this? Is there a better / more efficient / quicker way? Is it possible to convert this to an associative array for easy access?
Preface
Before you do anything, (re)familiarise yourself with SimpleXML’s peculiar way of doing things. The best place to start is the SimpleXML basic usage manual page.
The example below shows you:
<rate>element object based on an attribute’s value, and how to display it.<rate>elements and displaying their values.Basic example code
The above example outputs:
(See this example running online)
XML to array
I see this being asked time and time and time again. Rather than turning a tree of
SimpleXMLElementobjects into some “friendly” array, please instead take the time to learn how to use SimpleXML: once you have done that, there is no need to take the intermediate step of turning the objects into arrays to work with. The “basic usage” page referred to above should get you going, but key points to know are:$parent->child$element["attr_name"](string) $element->child