Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to converting JSON text to PHP associative array

Tags:

json

php

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?

like image 688
Q_Mlilo Avatar asked Nov 24 '10 08:11

Q_Mlilo


People also ask

Which PHP function can convert a JSON string into an associative array?

The json_decode function is used for taking a JSON encoded string and converting it into a PHP variable. It has four parameters: json , assoc , depth , and options . Once the assoc parameter is TRUE, then the returned objects will be converted to associative arrays.

Can we convert JSON string to array?

Approach 1: First convert the JSON string to the JavaScript object using JSON. Parse() method and then take out the values of the object and push them into the array using push() method.

Is JSON associative array?

The json_decode() function returns an object by default. The json_decode() function has a second parameter, and when set to true, JSON objects are decoded into associative arrays.

How do I extract data from JSON with PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.


2 Answers

$assocArray = json_decode($data, true);

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

like image 167
VdesmedT Avatar answered Oct 04 '22 03:10

VdesmedT


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

like image 30
Horia Dragomir Avatar answered Oct 04 '22 03:10

Horia Dragomir