由于某些原因,需要在PHP7中运行我的NodeJS项目的一小部分。
我知道我可以制作一个内部API,但这会增加网络依赖性。

为了解决这个问题,我发现可以做到这一点

php test.php


如何为该PHP文件提供JSON输入,其中数据存储在一个JS变量而不是文件中,并在另一个JS变量中接收输出。

function runPHP(jsonString){
    ....what to write here
    ...
    return output_string;
}



  注意:请不要建议查询参数,因为数据太大。

最佳答案

我假设您想从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/

10-11 22:26
查看更多