It was my colleague Dynom who saved the day for me. He pointed me towards the second optional parameter of the attributes() method of the SimpleXMLElement object. Given the following snippet (within a larger snippet):
<p><a href="/weblog/edit/id/something_or_other">a text</a></p>
I was using the first parameter of attributes (the namespace) to let SimpleXML know from which namespace I wanted to get the attributes:
$attributes = $xml->a->attributes('xlink' );
echo $attributes['href'];
This didn’t work. $attributes[‘href’] didn’t exist, and var_dump-ing the $attributes array returned an empty array. However, clearly I should learn to read better, because the manual does mention the second parameter $is_prefix, which is a boolean that indicates if the attributes are actually prefixed by the namespace. As, in the above case, this is true, I have to set it to true (it defaults to false). So with this it worked:
$attributes = $xml->a->attributes('xlink', true);
echo $attributes['href'];
These are the kinds of details that you can get stumped on for ages, so I hope that people reading this will keep it in mind and remember it when they encounter a similar situation 🙂
Leave a Reply