extending PHP's SimpleXML

Posted by phillip Tue, 27 Mar 2007 05:43:00 GMT

PHP’s XML workhorse, SimpleXML can be extended. you can supply a class of your own for PHP to wrap all XML nodes instead of the default SimpleXMLElement. do this by passing the desired class name as a string to the simplexml_load_(file|string) methods:

<?php

class MySimpleXMLElement extends SimpleXMLElement
{     
   // extending parent method
   public function xpath($path)
   {  
      echo "evaluating the following xpath expression: $path\n";
      $result = parent::xpath($path);
      echo "found " . sizeof($result) . " nodes";
      return $result;
   }
}

$doc = simplexml_load_file('products.xml', 'MySimpleXMLElement');
// calling an extended method
$nodes = $doc->xpath('//articles/article/shortdesc');
echo "\n";

// calling a parent method
echo $doc->root->getName();
echo "\n";

?>

i didn’t poke around in the internals of the parent class too much, no idea how well that would. on the other hand, in many cases it might be a better solution to delegate to SimpleXML instead of inheriting and extending from it.

Posted in , | Tags , ,