I have the following JSON Object stored in a text file(data.txt):
{"player":"black","time":"0","from":"2c","to":"3d"}
Which i read using php:
<?php
$data = file_get_contents('data.txt');
?>
Question: Is there an easy way to convert $data
to a PHP associative array. I have tried using json_decode($data);
but that did not work, any suggestions?
$assocArray = json_decode($data, true);
第二个参数将结果设置为对象(false,默认值)或关联数组(true)。
Try: json_decode($data, true)
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
You can use this function to convert array from json in php, this can validate if the provided string is valid json or not:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.