Reputation: 12445
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?
Upvotes: 1
Views: 3097
Reputation: 51950
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
$query = simplexml_load_file('…');
// Get a <rate> element by its id attribute
$rates = $query->xpath('results/rate[@id = "XAUGBP"]');
$rate = $rates[0];
echo "$rate->Name was at $rate->Rate at $rate->Time on $rate->Date\n";
echo "-----\n";
// or, loop over all of the <rate> elements
foreach ($query->results->rate as $rate) {
echo "$rate->Name was at $rate->Rate at $rate->Time on $rate->Date\n";
}
The above example outputs:
XAU to GBP was at 1030.5784 at 5:55pm on 7/27/2012
-----
XAU to GBP was at 1030.5784 at 5:55pm on 7/27/2012
XAG to GBPZ 999 N was at 17.4502 at 5:55pm on 7/27/2012
XPT to GBPZ 999 was at 893.3414 at 5:55pm on 7/27/2012
XPD to GBP1 UZ was at 362.652 at 5:55pm on 7/27/2012
(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 SimpleXMLElement
objects 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
Upvotes: 2
Reputation:
XPath query should be "//query/results/rate[contains(@id, 'XAUGBP')]"
Upvotes: 1