I've run into an issue with PHP and object key access.
I have a SimpleXMLElement that returns an array of 11 SimpleXMLElements as follows:
SimpleXMLElement Object
(
[Power.AssetToAssetMapping] => Array
(
[0] => SimpleXMLElement Object
(
[AssetToAssetMappingID] => 36063
[Supplier_x0020_Asset_x0020_Type] => Powerstrip
[..etc..]
When I try to isolate the array using braces, I only see the first record of the array. The other 10 are never output:
print_r( $xml->{'Power.AssetToAssetMapping'} );
When I use the whole object, I see all 11 records:
print_r( $xml );
Is there another way to access the first child of this object? I can foreach over each child of the object returned in $xml and get to each element just fine, but it seems like this is a bug in PHP.
Just convert SimpleXMLElement Object to Array ;)
$xml = (array)$xml;
When you use the print_r
:
print_r( $xml->{'Power.AssetToAssetMapping'} );
SimpleXML will magically offer only the first matching element here. However, technically, using that value is actually a SimpleXMLElement
that will allow you to access either all (in form of a Traversable
) or a specific one via (or similar to) ArrayAccess
on a zero-based, integer index:
$xml->{'Power.AssetToAssetMapping'}[1];
That for example is the second <Power.AssetToAssetMapping>
element under the root element.
foreach ($xml->{'Power.AssetToAssetMapping'} as $element) {
// each element
print_r($element);
}
That for example is an iteration over are all <Power.AssetToAssetMapping>
elements under the root element, from first to last.
Take note that this behavior is specific to SimpleXMLElement
. A simple stdClass
does not behave in the same fashion.