我正尝试使用PHP作为命令行脚本。我传递一个json字符串给它,并且我正在尝试读取这些值,但是当我执行echo $user_inputs["foo"];
时出错,这是为什么?我忘了关于json_decode的一些事情,还是关于使用STDIN?回应给予PHP脚本的STDIN
my_test.php
// Get the STDIN.
$stdin = fopen('php://stdin', 'r');
// Initialize user_inputs_json which will be the entire stdin.
$user_inputs_json = "";
// Read all of stdin.
while($line = fgets($stdin)) {
$user_inputs_json .= $line;
}
// Create the decoded json object.
$user_inputs = json_decode($user_inputs_json);
// Try to echo a value. This is where I get my error (written out below).
echo $user_inputs["foo"];
fclose($stdin);
运行此命令行通过JSON到它:
$ echo '{"foo":"hello world!", "bar": "goodnight moon!"}' | php my_test.php
我得到这个错误:
Fatal error: Cannot use object of type stdClass as array in /Users/don/Desktop/my_test.php on line 20
'$ user_inputs-> foo'应该在这种情况下做到这一点。没有? – Ohgodwhy 2014-10-10 21:32:32