PHP中阅读JSON [重复]

tuwxkamq  于 4个月前  发布在  PHP
关注(0)|答案(2)|浏览(51)

此问题在此处已有答案

How to extract and access data from JSON with PHP?(2个答案)
昨天就关门了。
我尝试了一些不同的东西,我有一些Geojson,我试着用PHP从中提取信息。JSON看起来像这样:

{ "type": "Feature", "properties": { "PLAN_NO": "HP4002" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -1.269204733799349, 60.69917889926522 ], [ -1.26900101889315, 60.708156244292169 ], [ -1.25068179301849, 60.708055130595085 ], [ -1.250890613767938, 60.699077822506901 ], [ -1.269204733799349, 60.69917889926522 ] ] ] } 
},
{ "type": "Feature", "properties": { "PLAN_NO": "HP4003" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -1.26900101889315, 60.708156244292169 ], [ -1.268797174460049, 60.71713348706259 ], [ -1.250472839496742, 60.717032336406525 ], [ -1.25068179301849, 60.708055130595085 ], [ -1.26900101889315, 60.708156244292169 ] ] ] } 
}

个字符
我试图得到PLAN_NO和每个的坐标。我看到的所有json示例都有这样的内容:

"properties": [ {"PLAN_NO": "HP002"}, etc ]


所以你可以做

foreach ($features as $feature) {
    $plan = $feature['PLAN_NO'];
}


由于我的JSON格式有点不同,我不知道如何使用它。感谢您的任何正确的指导。

ylamdve6

ylamdve61#

在JSON数据中,PLAN_NO嵌套在properties中,properties嵌套在每个Feature中。因此,您需要使用$feature['properties']['PLAN_NO']访问它。类似地,坐标嵌套在geometry中,geometry也嵌套在每个Feature中。

foreach ($features as $feature) {
    $plan = $feature['properties']['PLAN_NO'];
    $coordinates = $feature['geometry']['coordinates'];
}

字符串

e4yzc0pl

e4yzc0pl2#

file_get_contents()在失败时返回false,如果有点复杂,则返回json_decode(),但我建议您将其配置为在错误时抛出异常,或者如果您使用的是非常旧的PHP版本(低于7.3),请使用json_last_error()和/或json_last_error_msg()手动检查错误。
在您的案例中:

$filename = 'test.json';
$data = file_get_contents($filename);
if ($data === false) {
    throw new \RuntimeException("Could not read input file: $filename");
}
$features = json_decode($data, associative: true, flags: JSON_THROW_ON_ERROR);

字符串
Fatal error:Uncaught JsonException:错误
.因为你分享的JSON不太正确。(你的结果可能会有所不同,因为它不是实际的JSON,而只是一个片段)。
您可以使用JSON validator进行双重检查。

相关问题