运行 PHP Node.js(或 CMD)中的脚本?
Run PHP script in Node.js (or CMD)?
由于某些原因需要 运行 我的 NodeJS 项目的一小部分 PHP7 .
我知道我可以创建一个内部 API 但这会增加网络依赖性。
为了解决这个问题,我发现可以这样做
php test.php
我如何向这个[=提供JSON输入 35=] file 其中数据存储在 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"}');
这需要一些润色和错误处理...
由于某些原因需要 运行 我的 NodeJS 项目的一小部分 PHP7 . 我知道我可以创建一个内部 API 但这会增加网络依赖性。
为了解决这个问题,我发现可以这样做
php test.php
我如何向这个[=提供JSON输入 35=] file 其中数据存储在 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"}');
这需要一些润色和错误处理...