eleanor
eleanor

Reputation: 1534

PHP - Building Include/Require Tree

Currently I'm parsing PHP code and would live to build a include/require and functions tree: by include/require tree I mean a tree, where it's evident which file includes from the other files - here I have to watch out for loops, but it doable. Let's say I have a file a.php, which in turn includes b.php and c.php and c.php futher includes d.php, the tree should be constructed in a way where the hierarchy is shown.

It would also be great if this could be done for functions as well, where one function calls the second function, which in turn calls the third function.

My question is whether such a tool or a script is already available, because I don't really need anything fancy, but on the other hand I don't want to reinvent the wheel.

Upvotes: 2

Views: 967

Answers (2)

The PHP built in function get_included_files() would seem to most useful for this situation. Example:

$included_files = get_included_files();

foreach ($included_files as $filename) { echo "$filename\n"; }

Upvotes: 0

ndm13
ndm13

Reputation: 1239

I'm thinking that maybe you could use something like REGEX to parse the PHP file (not sure if there's something like DOMDocument for PHP that would make it easier) that gets the contents of any include or require. Something like this:

function make_tree($php_file){
    //specify output file
    $output = ""

    //set counter
    $counter = 1;

    //make REGEX or other parsing array of
    //all the include, include_once,
    //require, and require_once elements

    foreach($regex_array[] as $url){
        $output .= $counter . ": Page included/required " . $url . ".";

        //run make_tree on subpage
        make_tree($url);

        //increment counter
        $counter = $counter + 1;
    }

    //output the output
    return $output;
}

This is very rough and will probably need some revisions, but it seems like it should work. Sample output:

1: Page included/required first_require.php.     //required by your first document
1: Page included/required req1.php               //required by first_require.php
2: Page included/required req2.php               //required by first_require.php
1: Page included/required penguin.php            //required by req2.php
3: Page included/required req3.php               //required by first_require.php

There are some major issues that could probably be fixed with nested arrays, but I'm not sure how to implement it right now.

Upvotes: 1

Related Questions