skip to Main Content

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


  1. In your JSON data, the PLAN_NO is nested inside properties, which is nested inside each Feature. So, you need to access it using $feature['properties']['PLAN_NO']. Similarly, the coordinates are nested inside geometry, which is also nested inside each Feature.

    foreach ($features as $feature) {
        $plan = $feature['properties']['PLAN_NO'];
        $coordinates = $feature['geometry']['coordinates'];
    }
    
    Login or Signup to reply.
  2. 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:

    $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: Syntax error

    … 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search