Support » Developing with WordPress » using json in plugin

  • jackbluehouse2019

    (@jackbluehouse2019)


    Hello wp specialists,
    I have this json string in a variable $page_content :
    {"type":"FeatureCollection","features":[{"type":"Feature","properties":{"postcode":["38660"],"citycode":["38395","38"],"city":["plateau-des-petites-roches"],"toponym":"Plateau-des-Petites-Roches","extrafields":{"population":2380,"status":"","cleabs":"COMMUNE_0000002200276548","names":["plateau-des-petites-roches"]},"category":["administratif","commune"],"_score":1,"distance":0,"_type":"poi"},"geometry":{"type":"Point","coordinates":[5.893712562,45.333663943]}}]}

    I need the code to retrieve the data associated with “city”.
    I’ve tried this:

    $obj = json_decode($page_content);
    echo $obj->type;

    it returns FeaturesCollections but I need what’s linked to “city”…
    Help!
    Thanks
    Jacques from Grenoble France

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    Do var_dump( $obj->type ); to see what data structure you’re dealing with and go from there. The next step might be $obj->type['city']. Or maybe there’s another step. Or it may be an object property instead of an array element. IDK, parsing JSON on sight isn’t my strong suit 🙂 But examining what you get at each step will get you there.

    Thread Starter jackbluehouse2019

    (@jackbluehouse2019)

    var_dump( $obj->type );
    returns:
    string(17) “FeatureCollection”
    var_dump( $obj->type['city']);
    returns:
    Warning: Illegal string offset ‘city’ in /Applications/MAMP…
    string(1) “F”

    Moderator bcworkz

    (@bcworkz)

    OK then, $type prop is entirely the wrong branch. Back up a step and dump the entire $obj, then work your way down the correct branch.

    Thread Starter jackbluehouse2019

    (@jackbluehouse2019)

    Thanks bcwokz,
    I sorted out, the right branch is:

    foreach ($obj->features as $index => $feature){
    	$city = $feature->properties->city;
    	echo "city : ".$city;
    }
Viewing 4 replies - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.