[英]How to converting JSON text to PHP associative array
I have the following JSON Object stored in a text file(data.txt): 我将以下JSON对象存储在文本文件(data.txt)中:
{"player":"black","time":"0","from":"2c","to":"3d"}
Which i read using php: 我用php读到的:
<?php
$data = file_get_contents('data.txt');
?>
Question: Is there an easy way to convert $data
to a PHP associative array. 问题:是否有一种简单的方法可以将
$data
转换$data
PHP关联数组。 I have tried using json_decode($data);
我尝试过使用
json_decode($data);
but that did not work, any suggestions? 但那没用,有什么建议吗?
$assocArray = json_decode($data, true);
第二个参数将结果设置为对象(false,默认值)或关联数组(true)。
Try: json_decode($data, true)
尝试:
json_decode($data, true)
http://www.php.net/manual/en/function.json-decode.php http://www.php.net/manual/en/function.json-decode.php
It worked for me. 它对我有用。 Also, make sure your PHP version has json_encode / json_decode
另外,请确保您的PHP版本具有json_encode / json_decode
You can use this function to convert array from json in php, this can validate if the provided string is valid json or not: 您可以使用此函数从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.