The SimpleXML examples page, section "Example #5 Using attributes" states:
Access attributes of an element just as you would elements of an array.
And the example #1 in SimpleXMLElement::children()
works using $element['attribute']
syntax to access children's attributes;
Adding a namespace to that code, will disable the access to attributes:
$xml = new SimpleXMLElement(
'<person xmlns:a="foo:bar">
<a:child role="son">
<a:child role="daughter"/>
</a:child>
<a:child role="daughter">
<a:child role="son">
<a:child role="son"/>
</a:child>
</a:child>
</person>');
foreach ($xml->children('a', true) as $second_gen) {
echo ' The person begot a ' . $second_gen['role'];
foreach ($second_gen->children('a', true) as $third_gen) {
echo ' who begot a ' . $third_gen['role'] . ';';
foreach ($third_gen->children('a', true) as $fourth_gen) {
echo ' and that ' . $third_gen['role'] . ' begot a ' . $fourth_gen['role'];
}
}
}
// results
// The person begot a who begot a ; The person begot a who begot a ; and that begot a
// expected
// The person begot a son who begot a daughter; The person begot a daughter who begot a son; and that son begot a son
There's is plenty of questions here pointing the same solution, to use the SimpleXMLElement::attributes()
function instead of accessing as an array, but none answers explains why.
This different behavior when using namespaces is a bug? Is the documentation outdated? Should we always use SimpleXMLElement::attributes()
and avoid the recommended array-like syntax?
Note: I'm using PHP 5.5.9-1ubuntu4.9
.