trình đọc mảng php
Tiện ích JS nhỏ này đọc các tệp và chuỗi PHP chứa các mảng và trả về một đối tượng JavaScript
Nó sử dụng glayzzle/php-parser để phân tích cú pháp PHP thành AST và sử dụng thông tin đó để trích xuất các mảng
Nó hỗ trợ cả mảng được lập chỉ mục và kết hợp cũng như các giá trị mảng, chuỗi, số và null
Cài đặt
Thư viện này được phân phối với npm
npm install php-array-reader --save
Cách sử dụng
Với một chuỗi PHP
const phpArrayReader = require('php-array-reader'); const phpString = `[ 'key' => 'string', 'indexed_array' => [ 'first', 'second' ], 'associative_array' => [ 'foo' => 'bar', 'hello' => 'world' ], 'also_supports' => null, 'and_numeric' => 42 ]`; const data = phpArrayReader.fromString(phpString);
data sẽ là đối tượng JS này
{ key: 'string', indexed_array: ['first', 'second'], associative_array: { foo: 'bar', hello: 'world' }, also_supports: null, and_numeric: 42 }
Với một tệp PHP
const phpArrayReader = require('php-array-reader'); const phpFile = './file.php'; const data = phpArrayReader.fromFile(phpFile);
Tệp PHP có thể trả về một mảng đơn, e. g
<?php return [ 'key' => 'string', 'indexed_array' => [ 'first', 'second' ], 'associative_array' => [ 'foo' => 'bar', 'hello' => 'world' ], 'also_supports' => null, 'and_numeric' => 42 ];
Điều này sẽ có kết quả tương tự như ví dụ fromString ở trên
Hoặc tệp PHP có thể bao gồm nhiều mảng được gán, e. g
<?php $first = [ 'key' => 'string', 'associative_array' => [ 'foo' => 'bar', 'hello' => 'world' ] ]; $second = [ 'index_array' => [ 'first','second' ], 'also_supports' => null, 'and_numeric' => 42 ];
Điều này sẽ trả về một đối tượng JS có tên biến là khóa cấp đầu tiên
{ first: { key: 'string', associative_array: { foo: 'bar', hello: 'world' } }, second: { index_array: ['first', 'second'], also_supports: null, and_numeric: 42 } }
Tất nhiên, bạn cũng có thể sử dụng phép hủy để gán kết quả cho hai biến
const phpArrayReader = require('php-array-reader'); const phpFile = './file.php'; const { first, second } = phpArrayReader.fromFile(phpFile);