2010-11-24 66 views
3

我都存储在一个文本文件(data.txt中)以下JSON对象:我读使用PHP如何JSON文本转换为PHP关联数组

{"player":"black","time":"0","from":"2c","to":"3d"} 

<?php 
    $data = file_get_contents('data.txt'); 
?> 

问题:有没有简单的方法将$data转换为PHP关联数组。我曾尝试使用json_decode($data);,但没有奏效,有什么建议?

+4

为什么` json_decode($ data)`不起作用? – 2010-11-24 08:25:53

+0

由于JSON来自文本文件,PHP将其作为字符串读取。 – 2010-11-24 08:26:57

回答

18
$assocArray = json_decode($data, true); 

第二个参数将结果设置为对象(false,default)或关联数组(true)。

0

您可以使用此功能阵列从JSON转换在PHP中,这可以验证如果提供的字符串是有效的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; 
}