7

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?

asked Nov 24, 2010 at 8:24
4
  • 4
    Why did json_decode($data) not work? Commented Nov 24, 2010 at 8:25
  • Because the JSON is coming from a text file and PHP reads it as a string. Commented Nov 24, 2010 at 8:26
  • You may have to encode the string into json. Then put it into an array.. Commented Nov 24, 2010 at 8:28
  • 3
    JSON === string. If your text file contains the string you have posted above, it should be json_decodable just fine. Commented Nov 24, 2010 at 8:30

3 Answers 3

33
$assocArray = json_decode($data, true);

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

answered Nov 24, 2010 at 8:32
Sign up to request clarification or add additional context in comments.

1 Comment

Make sure you don't get your single and double quotes mixed up: //valid JSON: $string = '{"foo": "bar", "cool": "attr"}'; //Invalid JSON: $string = "{'foo': 'bar', 'cool': 'attr'}"; See: json.org
3

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

answered Nov 24, 2010 at 8:34

Comments

0

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;
}
answered May 22, 2015 at 2:50

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.