How to convert JSON text to an associative array of PHP

I have the following JSON object stored in a text file (data.txt):

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

What I read with php:

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

Question: Is there an easy way to convert $datato an associative PHP array. I tried using json_decode($data);, but that didn't work, any suggestions?

+3
source share
3 answers
$assocArray = json_decode($data, true);

The second parameter sets the result as an object (false, default) or an associative array (true).

+18
source

Try: json_decode($data, true)

http://www.php.net/manual/en/function.json-decode.php

It worked for me. Also, make sure your version of PHP has json_encode / json_decode

+2
source

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;
}
0

Source: https://habr.com/ru/post/1776642/


All Articles