Home

Awesome

<h1 align="center">php-parser</h1> <p align="center"> <a title="npm version" href="https://www.npmjs.com/package/php-parser"><img src="https://badge.fury.io/js/php-parser.svg"></a> <a title="npm downloads" href="https://www.npmjs.com/package/php-parser"><img src="https://img.shields.io/npm/dm/php-parser.svg?style=flat"></a> <a title="Gitter" href="https://gitter.im/glayzzle/Lobby"><img src="https://img.shields.io/badge/GITTER-join%20chat-green.svg"></a> </p> <p align="center">This JavaScript library parses PHP code and converts it to an AST.</p>

Installation

This library is distributed with npm :

npm install php-parser --save

Usage

// initialize the php parser factory class
const fs = require("fs");
const path = require("path");
const engine = require("php-parser");

// initialize a new parser instance
const parser = new engine({
  // some options :
  parser: {
    extractDoc: true,
    php7: true,
  },
  ast: {
    withPositions: true,
  },
});

// Retrieve the AST from the specified source
const eval = parser.parseEval('echo "Hello World";');

// Retrieve an array of tokens (same as php function token_get_all)
const tokens = parser.tokenGetAll('<?php echo "Hello World";');

// Load a static file (Note: this file should exist on your computer)
const phpFile = fs.readFileSync("./example.php");

// Log out results
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 :

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.