I need to print arbitrary SimpleXML objects in a specific manner, with special handling of attribute nodes.
The problem is that SimpleXML elements and attri
Unfortunately there is no hidden property or method that allows identifying the type of node in SimpleXML. SimpleXML only uses one Class and elements do not have anything that point to their parents. If you try the below reflection you will see that there is nothing to distinguish element or attribute.
$element = new SimpleXMLElement('test ');
echo ReflectionObject::export($element);
$element = new SimpleXMLElement('test ');
echo ReflectionObject::export($element['attr']);
However if an element has attributes you can detect that. So you would have to assume that all elements passed in have attributes. With that assumption you could tell them apart.
$element = new SimpleXMLElement('test ');
echo ReflectionObject::export($element);
echo ReflectionObject::export($element['attr']);
This is the best I can come up with. Remember it's possible for an element with no attributes to still return false with this.
function isNotAttribute($simpleXML)
{
return (count($simpleXML->attributes()) > 0);
}
$element = new SimpleXMLElement('test ');
var_dump(isNotAttribute($element));
var_dump(isNotAttribute($element['attr']));
// returns
bool(true)
bool(false)