4 Nodes (and comments) implement the `JsonSerializable` interface. As such, it is possible to JSON
5 encode the AST directly using `json_encode()`:
10 use PhpParser\ParserFactory;
15 /** @param string $msg */
16 function printLine($msg) {
21 $parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
24 $stmts = $parser->parse($code);
26 echo json_encode($stmts, JSON_PRETTY_PRINT), "\n";
27 } catch (PhpParser\Error $e) {
28 echo 'Parse Error: ', $e->getMessage();
32 This will result in the following output (which includes attributes):
37 "nodeType": "Stmt_Function",
40 "nodeType": "Identifier",
54 "nodeType": "Expr_Variable",
71 "nodeType": "Stmt_Echo",
74 "nodeType": "Expr_Variable",
82 "nodeType": "Scalar_String",
101 "nodeType": "Comment_Doc",
102 "text": "\/** @param string $msg *\/",
114 The JSON representation may be converted back into an AST using the `JsonDecoder`:
119 $nodeDecoder = new PhpParser\NodeDecoder();
120 $ast = $nodeDecoder->decode($json);
123 Note that not all ASTs can be represented using JSON. In particular:
125 * JSON only supports UTF-8 strings.
126 * JSON does not support non-finite floating-point numbers. This can occur if the original source
127 code contains non-representable floating-pointing literals such as `1e1000`.
129 If the node tree is not representable in JSON, the initial `json_encode()` call will fail.
131 From the command line, a JSON dump can be obtained using `vendor/bin/php-parse -j file.php`.