由于某些原因需要在PHP7中运行我的NodeJS项目的一小部分。 我知道我可以创建一个内部 API,但这会增加网络依赖性。
为了解决这个问题,我发现可以这样做
php test.php
如何向此 PHP 文件提供 JSON 输入,其中数据存储在 JS 变量中不在文件中并在另一个 JS 变量中接收输出。
function runPHP(jsonString){
....what to write here
...
return output_string;
}
Note: Please, do not suggest Query parameters as the data is too large.
最佳答案
我假设您想从 Nodejs 进程调用 php scipt,以 JSON 格式发送一些参数,然后返回一些 JSON 并进一步处理它。
PHP 脚本:
<?php
// test.php
$stdin = fopen('php://stdin', 'r');
$json = '';
while ($line = fgets($stdin)) {
$json .= $line;
}
$decoded = \json_decode($json);
$decoded->return_message = 'Hello from PHP';
print \json_encode($decoded);
exit(0);
nodejs 脚本:
// test.js
function runPHP(jsonString) {
const spawn = require('child_process').spawn;
const child = spawn('php', ['test.php']);
child.stdin.setEncoding('utf-8');
child.stdout.pipe(process.stdout);
child.stdin.write(jsonString + '\n');
child.stdin.end();
}
runPHP('{"message": "hello from js"}');
这需要一些改进和错误处理......
关于node.js - 在 Node.js(或 CMD)中运行 PHP 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52243218/