Php json decodes txt file

I have the following file:

data.txt

{name:yekky}{name:mussie}{name:jessecasicas} 

I am new to PHP. Do you know how I can use the decoding of the above JSON with PHP?

My php code

 var_dump(json_decode('data.txt', true));// var_dump value null foreach ($data->name as $result) { echo $result.'<br />'; } 
+2
source share
6 answers

json_decode takes a string as an argument. Read in file with file_get_contents

 $json_data = file_get_contents('data.txt'); json_decode($json_data, true); 

You need to tweak the pattern string to be valid JSON by adding quotes around strings, commas between objects, and placing objects in a containing array (or object).

 [{"name":"yekky"}, {"name":"mussie"}, {"name":"jessecasicas"}] 
+19
source

As I said in your other question , you are not creating valid JSON. See my answer there for how to create it. This will lead to something like

 [{"name":"yekky"},{"name":"mussie"},{"name":"jessecasicas"}] 

(I don't know where your quotes disappeared, but json_encode() usually produces valid json)

And it's easy to read

 $data = json_decode(file_get_contents('data.txt'), true); 
+3
source

JSON data is invalid. You have several objects (and you do not have enough quotes), you need to somehow separate them before you json_decode to json_decode .

+1
source
 $data = json_decode(file_get_contents('data.txt'), true); 

But your JSON must be formatted correctly:

 [ {"name":"yekky"}, ... ] 
+1
source

This is not a valid JSON file, according to JSONLint . If so, you first need to read it:

 $jsonBytes = file_get_contents('data.json'); $data = json_decode($jsonBytes, true); /* Do something with data. If you set the second argument of json_decode (as above), it an array, otherwise an object. */ 
+1
source

You must read the file!

 $json = file_get_contents('data.txt'); var_dump(json_decode($json, true)); 
0
source

All Articles