views:

269

answers:

2

I'm doing some home-brewed automated documentation, since I have a codebase which is not very standard in its layout, and I was wondering what the best way was to read a PHP file and grab the contents of a comment block. The only way I can think to do it is to open the file and read it line-by-line, but thought that maybe there was some built-in magic that would parse the document for me, similar to the Reflection functions.

The basic layout of each file is like this:

<?php // $Id$
/**
 * Here is this script's documentation, with information in pseudo-javadoc
 * type tags and whatnot.
 *
 * @attr    something    some information about something
 * @attr    etc          etc etc
 */
 // rest of the code goes here.

It's important to note that these files don't have any functions or classes defined in them. The comments relate to the script as a whole.

+3  A: 

Check out Tokenizer.

To get all the comments in a file named test.php you'd do:

$tokens = token_get_all(file_get_contents("test.php"));
$comments = array();
foreach($tokens as $token) {
    if($token[0] == T_COMMENT || $token[0] == T_DOC_COMMENT) {
        $comments[] = $token[1];
    }
}
print_r($comments);
Paolo Bergantino
A: 

Have a look at the Reflection API that comes with PHP5, more specifically getDocComment():

PHP 5 comes with a complete reflection API that adds the ability to reverse-engineer classes, interfaces, functions and methods as well as extensions. Additionally, the reflection API also offers ways of retrieving doc comments for functions, classes and methods.

Also, depending on the size of your codebase, you might work less by modifying your comments to fit the phpDocumentor syntax, which is already seems pretty close to.

lpfavreau
it really is a very strange layout and requires a very specific output I'm afraid. The reflection functions seems to only apply to functions, classes, objects, etc. Can you pass it a file to parse?
nickf
+1 phpDocumentor, especially if the code is already formatter for it.
jmucchiello