fish man
fish man

Reputation: 2720

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 />';
    }

Upvotes: 3

Views: 49414

Answers (6)

brian_d
brian_d

Reputation: 11395

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"}]

Upvotes: 26

KingCrunch
KingCrunch

Reputation: 132051

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);

Upvotes: 3

phihag
phihag

Reputation: 288240

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.
*/

Upvotes: 1

powtac
powtac

Reputation: 41080

You have to read the file!

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

Upvotes: 0

Matthew
Matthew

Reputation: 48304

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

But your JSON needs to be formatted correctly:

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

Upvotes: 1

Halcyon
Halcyon

Reputation: 57703

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.

Upvotes: 1

Related Questions