php-parser
Search…
Overview
php-parser
This javascript library parses PHP code and convert it to AST.

Installation

This library is distributed with npm :
1
npm install php-parser --save
Copied!

Usage

1
// initialize the php parser factory class
2
var fs = require('fs');
3
var path = require('path');
4
var engine = require('php-parser');
5
6
// initialize a new parser instance
7
var parser = new engine({
8
// some options :
9
parser: {
10
extractDoc: true,
11
php7: true
12
},
13
ast: {
14
withPositions: true
15
}
16
});
17
18
// Retrieve the AST from the specified source
19
var eval = parser.parseEval('echo "Hello World";');
20
21
// Retrieve an array of tokens (same as php function token_get_all)
22
var tokens = parser.tokenGetAll('<?php echo "Hello World";');
23
24
// Load a static file (Note: this file should exist on your computer)
25
var phpFile = fs.readFileSync( './example.php' );
26
27
// Log out results
28
console.log( 'Eval parse:', eval );
29
console.log( 'Tokens parse:', tokens );
30
console.log( 'File parse:', parser.parseCode(phpFile) );
Copied!

Sample AST output

1
{
2
'kind': 'program',
3
'children': [
4
{
5
'kind': 'echo',
6
'arguments': [
7
{
8
'kind': 'string',
9
'isDoubleQuote': true,
10
'value': 'Hello World'
11
}
12
]
13
}
14
]
15
}
Copied!

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

  • prettier/plugin-php : Prettier PHP Plugin
  • babel-preset-php : Babel preset for converting PHP syntax to JavaScript. It can run subset of PHP in the browser or in Node.js
  • wp-pot : Generate pot file for WordPress plugins and themes
  • crane : PHP Intellisense/code-completion for VS Code
  • php-unparser : Produce code that uses the style format recommended by PSR-1 and PSR-2.
  • php-writer : Update PHP scripts from their AST
  • ts-php-inspections : Provide PHP code inspections written in typescript
  • php-reflection : Reflection API for PHP files
  • vscode-phpunit : vscode phpunit extension
You can add here your own project by opening an issue request.

License

This library is released under BSD-3 license clause.
Last modified 2yr ago