Read PHP Array into NodeJS function

Viewed 42

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.

1 Answers

Running the PHP script gets you nothing because the script doesn't output anything (there's no echo). So I think you need to extend the PHP script a little bit so that it does that.

<?php
$data = require("pathtofile/filename.php");
echo json_encode($data);

If you run that script from Node you should get some output that you can JSON.parse.

The best solution would be to store your data in JSON to begin with so both PHP and Node can read it.

Related