开发者

How to converting JSON text to PHP associative array

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开发者_JAVA技巧:

<?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);

The second parameter set the result as an object(false, default) or an associative array(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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜