php json解码txt文件
问题描述:
我有以下文件:
data.txt
{name:yekky}{name:mussie}{name:jessecasicas}
我对PHP相当陌生.您知道如何使用PHP解码上述JSON吗?
I am quite new at PHP. Do you know how I can use the decode the above JSON using PHP?
我的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_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);
您确实需要通过在字符串周围添加引号,对象之间的逗号并将对象放置在包含数组(或对象)的内部来将示例字符串调整为有效的JSON.
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"}]