简体   繁体   中英

php json decode a txt file

I have the following file:

data.txt

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

I am quite new at PHP. Do you know how I can use the decode the above JSON using PHP?

My PHP code

var_dump(json_decode('data.txt', true));// var_dump value null

foreach ($data->name as $result) {
        echo $result.'<br />';
    }

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

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

You do need to adjust your sample string to be valid JSON by adding quotes around strings, commas between objects and placing the objects inside a containing array (or object).

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

As I mentioned in your other question you are not producing valid JSON. See my answer there, on how to create it. That will lead to something like

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

(I dont know, where your quotes are gone, but json_encode() usually produce valid json)

And this is easy readable

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

Your JSON data is invalid. You have multiple objects there (and you're missing quotes), you need some way to separate them before you feed the to json_decode .

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

But your JSON needs to be formatted correctly:

[ {"name":"yekky"}, ... ]

That's not a valid JSON file, according to JSONLint . If it were, you'd have to read it first:

$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's an array,
otherwise an object.
*/

You have to read the file!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM