I’m tearing my hair out a bit, trying different things. I have some Geojson and am trying to pull info from it with PHP. The JSON looks like this:
{ "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 ] ] ] }
}
$filename = 'test.json';
$data = file_get_contents($filename);
$features = json_decode($data, true);
I am trying to get the PLAN_NO and the coordinates for each. All the json examples I see have something like this:
"properties": [ {"PLAN_NO": "HP002"}, etc ]
So you can do
foreach ($features as $feature) {
$plan = $feature['PLAN_NO'];
}
As my JSON format is a bit different, I don’t understand how to work with it. Thanks for any pointers in the right direction.
2
Answers
In your JSON data, the
PLAN_NO
is nested insideproperties
, which is nested inside eachFeature
. So, you need to access it using$feature['properties']['PLAN_NO']
. Similarly, the coordinates are nested insidegeometry
, which is also nested inside eachFeature
.You aren’t doing any error checking. file_get_contents() returns
false
on failure and json_decode() if a bit more complicated, but I’d suggest you configure it to throw exceptions on error, or if you are using a very old PHP version (less than 7.3), check errors manually with json_last_error() and/or json_last_error_msg().In your case:
… because the JSON you’ve shared is not quite right. (Your results may differ it that isn’t the actual JSON but just a fragment).
You can double check with a JSON validator.