php json 解码一个txt文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6312726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:57:49  来源:igfitidea点击:

php json decode a txt file

phpjson

提问by fish man

I have the following file:

我有以下文件:

data.txt

数据.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?

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

回答by brian_d

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

json_decode将字符串作为参数。读入文件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"}]

回答by KingCrunch

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

正如我在您的另一个问题中提到的,没有生成有效的 JSON。请参阅我的答案,了解如何创建它。这将导致类似的事情

[{"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);

回答by Halcyon

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.

您的 JSON 数据无效。您在那里有多个对象(并且您缺少引号),您需要某种方法将它们分开,然后再将它们提供给json_decode.

回答by Matthew

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

But your JSON needs to be formatted correctly:

但是您的 JSON 需要正确格式化:

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

回答by phihag

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

根据JSONLint,这不是有效的 JSON 文件。如果是这样,你必须先阅读它:

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

回答by powtac

You have to read the file!

你必须阅读文件!

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