I have been working on a small project involving PHP and XML,
the difficulty I am having comes from accessing attributes in a node.
Here is an example of accessing an attribute from a node:
<?php
$string = <<<XML
<a>
<foo name="one" game="lonely">1</foo>
</a>
XML;
$xml = simplexml_load_string($string);
foreach ($xml->foo[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
?>
In the above code, I cannot seem to understand the foo[0] bit.
For example, I am troubled over why you have to do foo[0]->att...
instead of just foo->att....
Thank you for your time,
– Michael Mitchell
The expression
$xml->fooallows to iterate over all<foo>child elements of the node in$xml. This can be zero or more child nodes:Therefore if you need only one specific of all these zero or more elements, you need to specify which one you mean. That can be done by adding the array braces and it’s zero-based position, here
$xml->foo[0]: