How to extend SimpleXML with missing functionality

  • Christian Stocker

Ever thought SimpleXML is too simple? Did you know, you can easily extend the SimpleXMLElement class?

From Rob Richards on the PHP internals mailinglist:

This [getting name and type of a Node] can be done extending the SimpleXMLElement and the functions are a whole 1 line of user code:
class cNode extends SimpleXMLElement {
  function getName() {
     return dom_import_simplexml($this)->nodeName;

  function getType() {
     return dom_import_simplexml($this)->nodeType;

$xml = '<root />';

$sxe = simplexml_load_string($xml, 'cNode');
print $sxe->getName()."n";
print $sxe->getType()."n";

dom_import_simplexml() and simplexml_import_dom() are zero-copy (on the internal dom tree) operations, therefore the performance loss is really negligible.

Qu’en pensez-vous?