Tuesday, October 3, 2006

Visualize the parse tree of a PHP source code

 wrote this xslt stylesheet to visualize the parse tree of a PHP source code.
The stylesheet can actually convert any XML tree to a graph in the dot format interpreted by Graphviz.

The code to vizualize nice parse tree with the PECL extension is the following:

//Loading the parse tree into a DOMDocument
$xml = new DOMDocument;
$xml->loadXML(parse_tree_from_file('order.php'), XML_OPTIONS);
//Loading the stylesheet into a DOMDocument
$xsl = new DOMDocument;
$xsl->load('toDot.xsl', XML_OPTIONS);
//Stylesheet processing
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl);
//Generating the image with graphviz
file_put_contents('order.dot', trim($proc->transformToXML($xml)));
`dot -T png -o order.png order.dot`
So if order.php contains the following source code:
class Order{
    private $items = array();
    private $amount = 0;
 
    public function addItem($reference, $quantity){
        $this->items[] = array($reference, $quantity);
        $this->amount += $quantity*Catalog::getPrice($reference);
    }
 
    public function getAmount(){
        return $this->amount;
    }
}
class Catalog{
    private static $priceList = array('Largo Winch' => 9.31, 'Astérix' => 8.46, 'XIII' => 8.70);
 
    public static function getPrice($reference){
        return self::$priceList[$reference];
    }
}
$myOrder = new Order;
$myOrder->addItem('Largo Winch',2);
$myOrder->addItem('Astérix',2);
You'll get the following tree:
To test this example at home, you need the Parse Tree pecl extension, an xslt proc and graphviz:
order.php is the original php file.
order.xml is the xml generated with the parse_tree_from_file function.
order.dot is the parse tree in dot format.
order.png is the png generated by graphviz.
toDot.xsl isthe stylesheet generating dot from xml.

10 comments:

  1. Plz tell me about PHP Ajax i mean how i can use it???

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Hey Nice Blog!! Thanks For Sharing!!!Wonderful blog & good post.Its really helpful for me, waiting for a more new post. Keep Blogging! vrey nice blog
    Ai & Artificial Intelligence Course in Chennai
    PHP Training in Chennai
    Ethical Hacking Course in Chennai Blue Prism Training in Chennai
    UiPath Training in Chennai

    ReplyDelete