How can I "import" a PHP array into a seperate NodeJS file?
Example:
example.php
<?php
return array(
'title' => 'Example Value',
'description' => 'Example Value'
);
My attempt was to read it through executing the file but then I only get an empty response
const runner = require('child_process');
const scriptPath = 'pathtofile/filename.php';
runner.exec('php ' + scriptPath, (err, phpResponse, stderr) => {
console.log(phpResponse);
})
Note that I cannot modify the PHP files.
My Answer:
read a PHP array into a NodeJS function?
One way to achieve this is by using a library like `php-serialize` to serialize the PHP array into a string, and then pass that string to your NodeJS function.
Here's an example of how you can do this:
1. In your PHP code, serialize the array:
php
$array = array('foo' => 'bar', 'baz' => 'qux');
$serializedArray = serialize($array);
echo $serializedArray;
2. In your NodeJS code, install the `php-serialize` library:
bash
npm install php-serialize
3. Use the `php-serialize` library to unserialize the PHP array in your NodeJS function:
javascript
const phpSerialize = require('php-serialize');
const serializedArray = 'a:2:{s:3:"foo";s:3:"bar";s:3:"baz";s:3:"qux";}';
const unserializedArray = phpSerialize.unserialize(serializedArray);
console.log(unserializedArray);
This will output:
javascript
{ foo: 'bar', baz: 'qux' }
This way, you can easily read a PHP array into a NodeJS function by serializing it in PHP and unserializing it in NodeJS.
Rate this post
5 of 5 based on 8307 votesComments