php-parser
This JavaScript library parses PHP code and converts it to an AST.
Installation
This library is distributed with npm :
npm install php-parser --save
Usage
const fs = require("fs");
const path = require("path");
const engine = require("php-parser");
const parser = new engine({
parser: {
extractDoc: true,
php7: true,
},
ast: {
withPositions: true,
},
});
const eval = parser.parseEval('echo "Hello World";');
const tokens = parser.tokenGetAll('<?php echo "Hello World";');
const phpFile = fs.readFileSync("./example.php");
console.log("Eval parse:", eval);
console.log("Tokens parse:", tokens);
console.log("File parse:", parser.parseCode(phpFile));
Sample AST output
{
'kind': 'program',
'children': [
{
'kind': 'echo',
'arguments': [
{
'kind': 'string',
'isDoubleQuote': true,
'value': 'Hello World'
}
]
}
]
}
API Overview
The main API exposes a class with the following methods :
- parseEval(String|Buffer) : parse a PHP code in eval style mode (without php open tags)
- parseCode(String|Buffer, String filename) : parse a PHP code by using php open tags.
- tokenGetAll(String|Buffer) : retrieves a list of all tokens from the specified input.
You can also pass options that change the behavior of the parser/lexer.
Documentation
Related projects
You can add here your own project by opening an issue request.
License
This library is released under BSD-3 license clause.