|
Posted by Andrew C on 10/30/06 14:24
Hi, folks.
I've encountered what seems to me to be something of an oddity while playing
around with XML parsing in PHP, and I wondered if any of you might be able
to clear up my confusion...
Here's a little code:
$xmlDoc = new DOMDocument();
$xmlDoc->load('widget_data.xml');
$widgets = $xmlDoc->getElementsByTagName('widget');
My understanding was that '$widgets' is an array of elements, and the
following 'foreach' iterates through that array (this works):
foreach ($widgets as $widget)
{
....
}
However, I get an error if I try to access '$widgets' using square-brackets,
e.g.:
$widget = $widgets[0];
(The error is: "Fatal error: Cannot use object of type DOMNodeList as
array".)
PHP confirms that the first element of the 'array' has an index/key of '0'
with the following (or similar), but won't let me access it directly using
'$widgets[0]':
foreach ($widgets as $key => $widget)
{
echo("<p>" . $key . "</p>\n");
}
Does anyone have an explanation as to why a DOMNodeList can be accessed like
an array using 'foreach', but won't allow square-brackets to be used? What
exactly *is* a DOMNodeList?
Thanks for any help.
A.
PS. I am aware that DOMNodeLists have an 'item()' method with which nodes
within the list can be referred to via index, but my confusion still stands
as to why I can't simply use '[]'s.
Navigation:
[Reply to this message]
|