PHP-Parser README

The project's README from github.com/nikic/PHP-Parser. As one markdown file: README.md.

PHP Parser

Coverage Status

This is a PHP parser written in PHP. Its purpose is to simplify static code analysis and manipulation.

Documentation for version 5.x (current; for running on PHP >= 7.4; for parsing PHP 7.0 to PHP 8.4, with limited support for parsing PHP 5.x).

Documentation for version 4.x (supported; for running on PHP >= 7.0; for parsing PHP 5.2 to PHP 8.3).

Features

The main features provided by this library are:

Quick Start

Install the library using composer:

php composer.phar require nikic/php-parser

Parse some PHP code into an AST and dump the result in human-readable form:

<?php
use PhpParser\Error;
use PhpParser\NodeDumper;
use PhpParser\ParserFactory;

$code = <<<'CODE'
<?php

function test($foo)
{
    var_dump($foo);
}
CODE;

$parser = (new ParserFactory())->createForNewestSupportedVersion();
try {
    $ast = $parser->parse($code);
} catch (Error $error) {
    echo "Parse error: {$error->getMessage()}\n";
    return;
}

$dumper = new NodeDumper;
echo $dumper->dump($ast) . "\n";

This dumps an AST looking something like this:

array(
    0: Stmt_Function(
        attrGroups: array(
        )
        byRef: false
        name: Identifier(
            name: test
        )
        params: array(
            0: Param(
                attrGroups: array(
                )
                flags: 0
                type: null
                byRef: false
                variadic: false
                var: Expr_Variable(
                    name: foo
                )
                default: null
            )
        )
        returnType: null
        stmts: array(
            0: Stmt_Expression(
                expr: Expr_FuncCall(
                    name: Name(
                        name: var_dump
                    )
                    args: array(
                        0: Arg(
                            name: null
                            value: Expr_Variable(
                                name: foo
                            )
                            byRef: false
                            unpack: false
                        )
                    )
                )
            )
        )
    )
)

Let's traverse the AST and perform some kind of modification. For example, drop all function bodies:

use PhpParser\Node;
use PhpParser\Node\Stmt\Function_;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitorAbstract;

$traverser = new NodeTraverser();
$traverser->addVisitor(new class extends NodeVisitorAbstract {
    public function enterNode(Node $node) {
        if ($node instanceof Function_) {
            // Clean out the function body
            $node->stmts = [];
        }
    }
});

$ast = $traverser->traverse($ast);
echo $dumper->dump($ast) . "\n";

This gives us an AST where the Function_::$stmts are empty:

array(
    0: Stmt_Function(
        attrGroups: array(
        )
        byRef: false
        name: Identifier(
            name: test
        )
        params: array(
            0: Param(
                attrGroups: array(
                )
                type: null
                byRef: false
                variadic: false
                var: Expr_Variable(
                    name: foo
                )
                default: null
            )
        )
        returnType: null
        stmts: array(
        )
    )
)

Finally, we can convert the new AST back to PHP code:

use PhpParser\PrettyPrinter;

$prettyPrinter = new PrettyPrinter\Standard;
echo $prettyPrinter->prettyPrintFile($ast);

This gives us our original code, minus the var_dump() call inside the function:

<?php

function test($foo)
{
}

For a more comprehensive introduction, see the documentation.

Documentation

  1. Introduction
  2. Usage of basic components

Component documentation:

PHP-Parser (nikic/PHP-Parser)

parsing
Searching Database…

What is this?A parser written in PHP that turns PHP code into an abstract syntax tree (AST). Its purpose is to simplify static code analysis and manipulation of PHP code.
Is it a library I call from my own code, or a ready-made analyzer tool?It's a library: you install it with Composer and drive it from PHP code. Parsing, AST traversal, modification and code generation all happen through its API — there is no standalone binary.
How do I get started with it?Install with php composer.phar require nikic/php-parser, then follow the quick start: parse code into an AST, dump it in human-readable form or walk it with node visitors, modify it, and convert it back to PHP code.
Which PHP versions does it need, and which PHP can it parse?The current 5.x line runs on PHP >= 7.4 and parses PHP 7.0 to PHP 8.4, with limited support for parsing PHP 5.x. The older 4.x line runs on PHP >= 7.0 and parses PHP 5.2 to PHP 8.3.
What happens if the code I feed it contains syntax errors?It does not stop at the first error: invalid code can be parsed into a partial AST. The docs also cover error recovery and column information for errors, which matters for linter-style tooling.
What can I do with the AST once I have it?Dump it in human-readable form, convert it back to PHP code, traverse and modify it with node visitors, resolve namespaced names, evaluate constant expressions, convert it to and from JSON, or use builders to construct AST nodes for code generation.
Can I edit code without ruining its formatting?Yes — formatting can be preserved for partially changed ASTs. In the README's quick start, a modified AST is converted back to PHP code that matches the original file minus the removed vardump() call.
Does it know where each node sits in the original source?Yes, the AST contains accurate location information, and errors come with column information — handy for precise diagnostics and IDE-style tooling.
Creator
nikic
Size
7.4 MB
Stars
17.5K
Age
15y
Commits · 90 Days