[英]php json decode a txt file
我有以下文件:
数据.txt
{name:yekky}{name:mussie}{name:jessecasicas}
我是 PHP 的新手。 你知道我如何使用 PHP 对上面的 JSON 进行解码吗?
我的 PHP 代码
var_dump(json_decode('data.txt', true));// var_dump value null
foreach ($data->name as $result) {
echo $result.'<br />';
}
json_decode将字符串作为参数。 使用file_get_contents
读入文件
$json_data = file_get_contents('data.txt');
json_decode($json_data, true);
您确实需要通过在字符串周围添加引号、对象之间的逗号并将对象放置在包含数组(或对象)中来将示例字符串调整为有效的 JSON。
[{"name":"yekky"}, {"name":"mussie"}, {"name":"jessecasicas"}]
正如我在您的其他问题中提到的,您没有生产有效的 JSON。 在那里查看我的答案,了解如何创建它。 这将导致类似的事情
[{"name":"yekky"},{"name":"mussie"},{"name":"jessecasicas"}]
(我不知道,你的引号在哪里,但json_encode()
通常会产生有效的 json)
这很容易阅读
$data = json_decode(file_get_contents('data.txt'), true);
您的 JSON 数据无效。 您在那里有多个对象(并且您缺少引号),您需要一些方法将它们分开,然后再将它们提供给json_decode
。
$data = json_decode(file_get_contents('data.txt'), true);
但是您的 JSON 需要正确格式化:
[ {"name":"yekky"}, ... ]
根据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.
*/
你必须阅读文件!
$json = file_get_contents('data.txt');
var_dump(json_decode($json, true));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.