I have an XML file as follows:
<Main>
<SubMain>
<First>10570</First>
<Time>07:33:51</Time>
<Result>500</Result>
<Taken>8:14</Taken>
<Results>
<int>100</int>
<int>100</int>
<int>85</int>
<int>100</int>
<int>100</int>
<int>100</int>
<int>100</int>
</Results>
</SubMain>
</Main>
That I am loading from a file into PHP using simplexml_load_file:
$xml=simplexml_load_file("note.xml") or die("Error: Cannot create object");
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child->First . $child->Time . $child->Taken ."<br>";
}
When I load in the Results row I am not getting any values returned, how do I step into this sub-array? Sorry if it's a daft question but has had me stumped today!
Edit: Removed the typo since it does not exist in the code, also to be clear the First, Time, Result etc are returning the expected values, it is the sub array (Results) I can not seem to pull data from.
All values returned when using SimpleXML are SimpleXMLElement
objects, which can be cast to native types (e.g. var_dump($xml->SubMain->First);
). It also implements Traversable
so it can be used in foreach loops.
To get the <int>
values, you will need to loop over the children of <Result>
:
foreach ($xml->SubMain->Results->children() as $result) {
// $result is a SimpleXMLElement object, needs casting
var_dump(intval($result));
}
You can also cast directly to an array, but note that you will have an array of strings:
$ints = (array) $xml->SubMain->Results->int;
var_dump($ints); // actually strings
So you could do something like this:
$ints = array_map('intval', (array) $xml->SubMain->Results->int);
var_dump($ints);