arrays - 将 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);
解决方案
更改您的 shell_exec 以转义 json,如下所示:
shell_exec('xvfb-run node app.js ' . escapeshellarg($json_titles));
这会转义 JSON 中的双引号,以便将它们正确传递给节点。
每次将变量传递到命令行时都应该这样做,以减少错误和安全风险。
编辑:正如 OP 所发现的,Node 还必须解析 JSON,因为它将参数作为字符串获取。这可以在节点脚本中完成,如下所示:
ParsedTitles = JSON.parse(getTitles);
推荐阅读
- python - opencv 在 macOS 中抛出错误 - Mojave
- unity3d - 简单的统一移动功能不起作用
- jquery - 数据表“第 0 行第 0 列请求的未知参数‘UserNo’”。(使用 asp.net mvc 核心)
- material-ui - 我们如何将 data-testid 添加到 textField 组件的错误字段中
- php - 在 php 中显示具有不同名称和一个后缀的所有会话
- html - 使父级适应 CSS 中子级的最大大小
- kendo-ui - 剑道摘要任务没有里程碑图标
- node.js - 如何在用户 ID 的帮助下找到数组中的对象..?
- azure-devops - 在 AzureDevops 中发布测试结果挂起
- spring-boot - 在集成测试开始之前运行 Firestore 模拟器