tags:

views:

40

answers:

1

I found the [] operator is sometimes confusing when it is used agains SimpleXMLElement object.

$level_a = $xml->children();
$level_a['name'];    # this returns the 'name' attribute of level_a (SimpleXmlElement object)
$level_a[0];         # this returns $level_a itself!
$level_a[1];         # this returns the second SimpleXmlElement object under root node. (Same level as level_a)

I can't find any documents about the numeric indexing usage of SimpleXmlElement class. Can anybody explain how those two worked?

Note that it seems this [num] operator of SimpleXmlElement just mimic the behavior of Array. I feel that this is not something stirred with Array, but the implementation of SimpleXmlElement class.

+1  A: 

I don't believe anything magical is going on here. An array in PHP can keyed by an integer, and may be keyed by a string as well. So the $xml->children() line is likely making an array of key-value attribute pairs in the form

foreach (attrs($element) as $attribute_name => $attribute_value)
    $array[$attribute_name] = $attribute_value;
$array[0] = $element;
// etc.
J Cooper
I don't think that I can always index PHP array by integer. Consider this: $myarray = array( 'a' => 'Apple', 'b' => 'Banana', 'c' => 'Cherry');print_r($myarray);for($i=0; $i<3; $i++) { print $myarray[$i] . "\n";}Subscribing by number doesn't work in this case.
solotim
But: `$myarray = array( 'a' => 'Apple', 0 => 'foo', 1 => 'bar' );` Keys are keys are keys, no matter if they're integers or strings.
Charles
Yes, Charles makes the point better. Edited to reflect.
J Cooper
OK, I understand what you said. But according to the specification of SimpleXmlElement, the children() function simply return yet another SimpleXmlElement object, not an array.
solotim
The documentation refers to it as a "psuedo-array" and says it "follows normal iteration rules." See http://www.php.net/manual/en/simplexmlelement.children.php
J Cooper
Thank you :) So, yes, there is some magic there. I need a specific description of the [] operator of SimpleXMLElement. I want to know how it works.
solotim
@solotim read through the "basic usage" manual page: http://php.net/simplexml.examples-basic
salathe