首页 > 解决方案 > 将 PHP 数组传递给 NodeJS

问题描述

如何将 PHP 数组传递给 Nightmare NodeJS 脚本?这就是我所在的位置:

 /*Original array $titles = 
 Array
 (
 [0] => title 1 with, a comma after with
 [1] => title 2
 [2] => title 3
 [3] => title 4
 )
 */

//PHP
$json_titles = json_encode($titles);
echo $json_titles;
//  Output:  ["title 1 with, a comma after with","title 2","title 3","title 4"]
// Pass to Nightmare NodeJS script with:
shell_exec('xvfb-run node app.js ' . $json_titles);

//NodeJS app.js:

const getTitles = process . argv[2];
console.log(getTitles)

// Output: [title 1 with, a comma after with,title 2,title 3,title 4]

如何在 PHP 中获取与 NodeJS 相同的数组?

正如您在下面看到的那样,Simon 使用 escapeshellarg 进行了救援。谢谢西蒙!最后,我在 Node JS 脚本中又多了一步。我需要: getTitles = JSON.parse(getTitles);

标签: arraysjsonnightmare

解决方案


更改您的 shell_exec 以转义 json,如下所示:

shell_exec('xvfb-run node app.js ' . escapeshellarg($json_titles));

这会转义 JSON 中的双引号,以便将它们正确传递给节点。

每次将变量传递到命令行时都应该这样做,以减少错误和安全风险。

编辑:正如 OP 所发现的,Node 还必须解析 JSON,因为它将参数作为字符串获取。这可以在节点脚本中完成,如下所示:

ParsedTitles = JSON.parse(getTitles);

推荐阅读