2014-10-10 35 views
-1

我正尝试使用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

+1

'$ user_inputs-> foo'应该在这种情况下做到这一点。没有? – Ohgodwhy 2014-10-10 21:32:32

回答

1

默认情况下,json_decode将JSON字符串转换为PHP对象。如果你想获得PHP阵列,使用json_decode的第二个参数:

$user_inputs_array = json_decode($user_inputs_json, true); 
0

如果你需要经常处理的JSON传递作为数组,将第二json_decode参数设置为true,迫使它解码作为array:

$user_inputs = json_decode($user_inputs_json, 1);