我都存储在一个文本文件(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);
,但没有奏效,有什么建议?
我都存储在一个文本文件(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);
,但没有奏效,有什么建议?
$assocArray = json_decode($data, true);
第二个参数将结果设置为对象(false,default)或关联数组(true)。
尝试: json_decode($data, true)
http://www.php.net/manual/en/function.json-decode.php
它为我工作。此外,请确保您的PHP版本有json_encode/json_decode
您可以使用此功能阵列从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;
}
为什么` json_decode($ data)`不起作用? – 2010-11-24 08:25:53
由于JSON来自文本文件,PHP将其作为字符串读取。 – 2010-11-24 08:26:57