[英]How to converting JSON text to PHP associative array
我將以下JSON對象存儲在文本文件(data.txt)中:
{"player":"black","time":"0","from":"2c","to":"3d"}
我用php讀到的:
<?php
$data = file_get_contents('data.txt');
?>
問題:是否有一種簡單的方法可以將$data
轉換$data
PHP關聯數組。 我嘗試過使用json_decode($data);
但那沒用,有什么建議嗎?
$assocArray = json_decode($data, true);
第二個參數將結果設置為對象(false,默認值)或關聯數組(true)。
嘗試: json_decode($data, true)
http://www.php.net/manual/en/function.json-decode.php
它對我有用。 另外,請確保您的PHP版本具有json_encode / json_decode
您可以使用此函數從php中的json轉換數組,這可以驗證提供的字符串是否有效json:
function convert_to_json($file, $in_array = True) {
if(file_exists($file)) {
$string = file_get_contents($file);
}else {
$string = $file;
}
$return_array = json_decode($string, $in_array);
if (json_last_error() == JSON_ERROR_NONE) {
return $return_array;
}
return False;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.