我正嘗試使用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