试图解析这个json文件并将其存储在php中

时间:2018-03-16 07:34:41

标签: php json swifty-json

我正在尝试解析这个json文件,但我无法将其存储为php中的数组。我一直遇到访问json文件对象的问题,因为我收到“非法字符串偏移'名称'错误。

我的代码如下:

这是我的json:

"{\"Data\":[{\"id\":21,\"name\":\"Parle G\",\"item_code\":\"PG4\"},{\"id\":22,\"name\":\"Dark Fentasy\",\"item_code\":\"DF\"}]}"

这是我尝试阅读文件的地方,但我无法访问对象

<?php

// Read JSON file
$json = file_get_contents('results.json');

//Decode JSON
$json_data = json_decode($json);

 //print_r($json_data);

echo $json_data[0]['name'];

?>

有人可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:2)

您需要使用:

$json_data = json_decode($json, true);

将json转换为关联数组

然后尝试:

echo $json_data['Data'][0]['name'];

答案 1 :(得分:1)

<?php

// Read JSON file
$json = file_get_contents('http://192.168.1.100:8080/demo_phonegap/webservices/result.json');

//Decode JSON
$json_data = json_decode($json, true);



    echo json_encode($json_data);



?>

在这里,您需要设置JSON文件的完整路径以读取JSON文件。 并使用$ json_data = json_decode($ json,true);解码JSON文件。

希望这会对你有所帮助。

答案 2 :(得分:-1)

如果你想将它作为一个数组使用,你必须将其转换为:

$json_data = (array) json_decode($json);

这将把JSON中的所有字段都放到PHP数组中:

Array ( [Data] => Array ( [0] => stdClass Object ( [id] => 21 [name] => Parle G [item_code] => PG4 ) [1] => stdClass Object ( [id] => 22 [name] => Dark Fentasy [item_code] => DF ) ) )

Alternativ您可以将数据转换为Object,因此您必须访问$json_data->Data[0]->name等字段

$json_data = (object) json_decode($json);

json_decode文档中了解详情:http://php.net/manual/en/function.json-decode.php

相关问题