NodeJS JSON.stringify将参数发送到PHP json_decode - 返回null

时间:2018-01-10 11:40:41

标签: php json node.js

我从一个nodejs应用程序调用一个PHP文件并发送参数,而其中一个参数应该是JSON(当然是字符串化的)

它没有按预期工作,因为字符串似乎是多个参数,需要转义或正确转义。

尝试分解问题,我创建了一个新的php文件,尝试从外部执行(在此示例中从命令行执行) - >

运行以下命令

php test.php {"access_token":"acccess_token","id_token":"id_token","refresh_token":"refresh-token","token_type":"token_type","expiry_date":1515578624982,"expires_in":3600}

这是失败的代码示例

<?php
$json = $argv[1];

$res = json_decode($json,true);
echo "CHECK-ERROR".json_last_error().PHP_EOL."-----".PHP_EOL;

echo "END RESULTS".PHP_EOL.$res.PHP_EOL."-------".PHP_EOL;

?>

这是输出

enter image description here

这么少有趣的事实: - 更改代码以将参数作为局部变量 - 工作正常。 - 将json放在单引号'{...}'中 - 工作正常。 - 使用'${jsonStringified}'从NodeJS调用php - 工作正常。 (因为它与上述的相同的想法

问题是其他解决方案是什么? (例如编码,转义)而不是这个小调整?

1 个答案:

答案 0 :(得分:0)

首先,您还没有定义$argv[1]。 其次,它不是PHP中的JSON,它是一个字符串,因此在PHP读取之前需要进行JSON编码。

命令行:

php test.php "{ \"access_token\": \"acccess_token\", \"id_token\": \"id_token\", \"refresh_token\": \"refresh-token\", \"token_type\": \"token_type\", \"expiry_date\": 1515578624982, \"expires_in\": 3600 }"

PHP脚本:

$json = json_decode($_SERVER['argv']['1'], true);

if (json_last_error()) { var_dump($_SERVER['argv']['1']); die(); }

echo "CHECK-ERROR".json_last_error().PHP_EOL."-----".PHP_EOL;

echo "END RESULTS".PHP_EOL.json_encode($json).PHP_EOL."-------".PHP_EOL;

应该做的伎俩。