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 d开发者_Python百科ecode 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));
精彩评论