2.1.1 • Published 6 months ago

php-array-reader v2.1.1

Weekly downloads
349
License
MIT
Repository
github
Last release
6 months ago

php-array-reader

Node.js CI

This small JS utility reads PHP strings containing arrays and returns a JavaScript object.

It uses glayzzle/php-parser to parse PHP into AST and uses that info to extract arrays.
It supports both indexed and associative arrays (i.e. lists and dictionaries/maps) and array, string, numeric and null values. Inline function calls are not evaluated but returned as raw strings. See the example below.

Installation

This library is distributed with npm :

npm install php-array-reader --save

Usage

import { fromString } from 'php-array-reader';

const phpString = `[
  'key' => 'string',
  'list' => [
    'first',
    'second'
  ],
  'dictionary' => [
    'foo' => 'bar',
    'hello' => 'world'
  ],
  'also_supports' => null,
  'and_numeric' => 42,
  'what_about' => true,
  'or' => false,
  'func' => strtoupper('abc'),
]`;
const data = fromString(phpString); 

data will be this JS object:

{
  key: 'string',
  list: ['first', 'second'],
  dictionary: {
    foo: 'bar',
    hello: 'world'
  },
  also_supports: null,
  and_numeric: 42,
  what_about: true,
  or: false,
  func: "strtoupper('abc')"
}

With a PHP file

Use fs.readFileSync or another file reading library to read the file, and pass that string into fromString, e.g.:

import { fromString } from 'php-array-reader';
import { readFileSync } from 'node:fs';

const phpFile = './file.php';
const phpString = readFileSync(phpFile);

const data = fromString(phpFile);

!NOTE Version 1.x of this library included a fromFile method that allowed you to read a file directly. This has been removed in version 2.x forward, because that method was a scope creep.

The PHP file can either return a single array, e.g.:

<?php
return [
   'key' => 'string',
   'list' => [
     'first',
     'second'
   ],
   'dictionary' => [
     'foo' => 'bar',
     'hello' => 'world'
   ],
   'also_supports' => null,
   'and_numeric' => 42
];

This will have the same result as the fromString example above.

Or the PHP file may consist of multiple assigned arrays, e.g.:

<?php
$first = [
    'key' => 'string',
    'dictionary' => [
        'foo' => 'bar',
        'hello' => 'world'
    ]
];
$second = [
    'list' => [
        'first','second'
    ],
    'also_supports' => null,
    'and_numeric' => 42  
];

This will return a JS object with the variable names as the first level keys:

{
  first: {
    key: 'string',
    dictionary: {
      foo: 'bar', 
      hello: 'world'
    }
  },
  second: {
    list: ['first', 'second'],
    also_supports: null,
    and_numeric: 42
  }
}
2.1.1

6 months ago

2.1.0

9 months ago

2.0.0

9 months ago

1.3.5

1 year ago

1.3.4

2 years ago

1.3.2

3 years ago

1.3.1

3 years ago

1.3.0

3 years ago

1.2.0

5 years ago

1.1.1

5 years ago

1.1.0

5 years ago

1.0.0

5 years ago