简体   繁体   English

php json 解码一个txt文件

[英]php json decode a txt file

I have the following file:我有以下文件:

data.txt数据.txt

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

I am quite new at PHP.我是 PHP 的新手。 Do you know how I can use the decode the above JSON using PHP?你知道我如何使用 PHP 对上面的 JSON 进行解码吗?

My PHP code我的 PHP 代码

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. json_decode将字符串作为参数。 Read in the file with file_get_contents使用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).您确实需要通过在字符串周围添加引号、对象之间的逗号并将对象放置在包含数组(或对象)中来将示例字符串调整为有效的 JSON。

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

As I mentioned in your other question you are not producing valid JSON.正如我在您的其他问题中提到的,您没有生产有效的 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) (我不知道,你的引号在哪里,但json_encode()通常会产生有效的 json)

And this is easy readable这很容易阅读

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

Your JSON data is invalid.您的 JSON 数据无效。 You have multiple objects there (and you're missing quotes), you need some way to separate them before you feed the to json_decode .您在那里有多个对象(并且您缺少引号),您需要一些方法将它们分开,然后再将它们提供给json_decode

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

But your JSON needs to be formatted correctly:但是您的 JSON 需要正确格式化:

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

That's not a valid JSON file, according to JSONLint .根据JSONLint ,这不是一个有效的 JSON 文件。 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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