2012-01-13 53 views
41

寫JSON我有以下的JSON文件中的list.txtPHP讀取和文件

{ 
"bgates":{"first":"Bill","last":"Gates"}, 
"sjobs":{"first":"Steve","last":"Jobs"} 
} 

如何添加"bross":{"first":"Bob","last":"Ross"}使用PHP我的檔案?

這是我到目前爲止有:

<?php 

$user = "bross"; 
$first = "Bob"; 
$last = "Ross"; 

$file = "list.txt"; 

$json = json_decode(file_get_contents($file)); 

$json[$user] = array("first" => $first, "last" => $last); 

file_put_contents($file, json_encode($json)); 

?> 

,給了我一個致命錯誤:在這條線不能使用類型爲stdClass的對象爲數組:

$json[$user] = array("first" => $first, "last" => $last); 

我使用PHP5。 2。有什麼想法嗎?謝謝!

回答

77

線索出現在錯誤信息中 - 如果您查看json_decode的文檔,請注意它可能需要第二個參數,它控制它是返回數組還是對象 - 它默認爲對象。

所以你的電話改變

$json = json_decode(file_get_contents($file), true); 

,它會返回一個關聯數組,你的代碼應該很好地工作。

+3

我討厭'json_decode'默認返回一個類而不是數組。這讓我每次在一個月內第一次使用'json_decode'就會出現問題。 – Tim 2012-01-14 00:01:15

7

您需要通過傳入參數true來使解碼函數返回一個數組。

json_decode(file_get_contents($file),true);

3

嘗試使用第二個參數json_decode功能:

$json = json_decode(file_get_contents($file), true); 
8

或者只是使用$ JSON作爲一個對象:

$json->$user = array("first" => $first, "last" => $last); 

這是它是如何沒有第二個參數返回(作爲stdClass的實例)。

3

這應該爲你工作得到list.txt文件

$headers = array('http'=>array('method'=>'GET','header'=>'Content: type=application/json \r\n'.'$agent \r\n'.'$hash')); 

$context=stream_context_create($headers); 

$str = file_get_contents("list.txt",FILE_USE_INCLUDE_PATH,$context); 

$str=utf8_encode($str); 

$str=json_decode($str,true); 

print_r($str); 
+0

我只是得到Array作爲我的輸出 – 2016-01-20 10:19:07

18

樣本的內容進行閱讀和PHP編寫JSON:

$json = json_decode(file_get_contents($file),TRUE); 

$json[$user] = array("first" => $first, "last" => $last); 

file_put_contents($file, json_encode($json)); 
+1

json_encode的第二個參數不是布爾值,所以寫'json_encode($ json,TRUE)'是錯誤的。 – 2017-02-01 17:01:28

+0

根據文檔(http://php.net/manual/en/function.json-decode.php),第二個參數是一個布爾值。 – 2017-07-27 17:24:17

1

當你想創建JSON格式它不得不請按照以下格式閱讀:

[ 
    { 
    "":"", 
    "":[ 
    { 
     "":"", 
     "":"" 
    } 
    ] 
    } 
] 
2

如果要顯示JSON數據定義合成你可以修改代碼爲:

file_put_contents($file, json_encode($json,TRUE)); 


$headers = array('http'=>array('method'=>'GET','header'=>'Content: type=application/json \r\n'.'$agent \r\n'.'$hash')); 

$context=stream_context_create($headers); 

$str = file_get_contents("list.txt",FILE_USE_INCLUDE_PATH,$context); 

$str1=utf8_encode($str); 

$str1=json_decode($str1,true); 



foreach($str1 as $key=>$value) 
{ 

    echo "key is: $key.\n"; 

    echo "values are: \t"; 
     foreach ($value as $k) { 

     echo " $k. \t"; 
     # code... 
    } 
     echo "<br></br>"; 
     echo "\n"; 

}