2

I am trying to extract the full_name value from the below json. I have been able to extract from the "query" section using this code.

echo $data->query->params->granularity;

This prints out neighbourhood.

But I am unable to echo the full_name. Im guessing this is because I have to do something different because of the [] but I'm new to this and not at sure what to do.

None of these seem to work.

foreach ($data['places'] as $item) { ough!
echo $item->result->places->contained_within->attributes->full_name;
echo $item->result->places->full_name;
echo $item->result->full_name;
echo $item->full_name;  
}

Any help would be greatly appreciated.

{
  "query": {
    "params": {
      "accuracy": 0,
      "coordinates": {
        "coordinates": [
          -122.42284884,
          37.76893497
        ],
        "type": "Point"
      },
      "granularity": "neighborhood"
    },
    "type": "reverse_geocode"
  },
  "result": {
    "places": [
      {
        "attributes": {

        },
        "bounding_box": {
          "coordinates": [
            [
              [
                -122.42676492,
                37.75983003
              ],
              [
                -122.420736,
                37.75983003
              ],
              [
                -122.420736,
                37.77226299
              ],
              [
                -122.42676492,
                37.77226299
              ]
            ]
          ],
          "type": "Polygon"
        },
        "contained_within": [
          {
            "attributes": {

            },
            "bounding_box": {
              "coordinates": [
                [
                  [
                    -122.51368188,
                    37.70813196
                  ],
                  [
                    -122.35845384,
                    37.70813196
                  ],
                  [
                    -122.35845384,
                    37.83245301
                  ],
                  [
                    -122.51368188,
                    37.83245301
                  ]
                ]
              ],
              "type": "Polygon"
            },
            "country": "United States",
            "country_code": "US",
            "full_name": "San Francisco, CA",
            "id": "5a110d312052166f",
            "name": "San Francisco",
            "place_type": "city"
          }
        ],
        "country": "United States",
        "country_code": "US",
        "full_name": "Mission Dolores, San Francisco",
        "id": "cf7afb4ee6011bca",
        "name": "Mission Dolores",
        "place_type": "neighborhood"
      }
    ]
  }
}
4
  • Your JSON is not valid... Commented Aug 23, 2014 at 18:57
  • Hi Nick, thanks for having a look. Thats not the full json its only a portion. The JSON came straight from twitter. you can see the all of it at this link.dev.twitter.com/docs/api/1.1/get/geo/reverse_geocode Commented Aug 23, 2014 at 19:03
  • $item->full_name might work hard to say without seeing full JSON Commented Aug 23, 2014 at 19:07
  • PHP's print_r() is a little more verbose and will help you determine how to get each variable. pastebin.com/3hyWTNGu Commented Aug 23, 2014 at 19:25

5 Answers 5

2

First problem the json is not valid. There are few issue. You can validate at following website: http://jsonlint.com/

And the json have two full name. So following code will help to extract those two full names.

$json = 'Assign the json here';
$json_array = json_decode($json);
echo $json_array->result->places[0]->contained_within[0]->full_name;
echo $json_array->result->places[0]->full_name;
  • Assign the valid json to the variable $json within single quot (') as json have double quot.

The tested code available here: http://sugunan.net/demo/json1.php

If we take your foreach example it need to be modified like follows. But that is not tested answer.

foreach ($data['places'] as $item) {
echo $item->contained_within[0]->full_name;
echo $item->full_name;
}

Following is the validated json of the above. Which had few unnecessary ",". And it missed few brackets.

{
"query": {
    "params": {
        "accuracy": 0,
        "coordinates": {
            "coordinates": [
                -122.42284884,
                37.76893497
            ],
            "type": "Point"
        },
        "granularity": "neighborhood"
    },
    "type": "reverse_geocode"
},
"result": {
    "places": [
        {
            "attributes": {},
            "bounding_box": {
                "coordinates": [
                    [
                        [
                            -122.42676492,
                            37.75983003
                        ],
                        [
                            -122.420736,
                            37.75983003
                        ],
                        [
                            -122.420736,
                            37.77226299
                        ],
                        [
                            -122.42676492,
                            37.77226299
                        ]
                    ]
                ],
                "type": "Polygon"
            },
            "contained_within": [
                {
                    "attributes": {},
                    "bounding_box": {
                        "coordinates": [
                            [
                                [
                                    -122.51368188,
                                    37.70813196
                                ],
                                [
                                    -122.35845384,
                                    37.70813196
                                ],
                                [
                                    -122.35845384,
                                    37.83245301
                                ],
                                [
                                    -122.51368188,
                                    37.83245301
                                ]
                            ]
                        ],
                        "type": "Polygon"
                    },
                    "country": "United States",
                    "country_code": "US",
                    "full_name": "San Francisco, CA",
                    "id": "5a110d312052166f",
                    "name": "San Francisco",
                    "place_type": "city"
                }
            ],
            "country": "United States",
            "country_code": "US",
            "full_name": "Mission Dolores, San Francisco",
            "id": "cf7afb4ee6011bca",
            "name": "Mission Dolores",
            "place_type": "neighborhood"
        }
    ]
}

}

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks so much for getting back to me.I have this but it only returns a blank page when run. <? include "library/twitteroauth.php"; //twitter app key details $consumer =""; $consumersecret = ""; $accesstoken = ""; $accesstokensecret = ""; $twitter = new TwitterOAuth($consumer,$consumersecret,$accesstoken,$accesstokensecret); $json = $twitter-> get('api.twitter.com/1.1/geo/…); $json_array = json_decode($json); echo $json_array->result->places[0]->contained_within[0]->full_name; echo $json_array->result->places[0]->full_name; ?>
is it working? Try to echo $json; and check wether the json is valid. At following web site pastebin.com
Hey yeah I got it to work by adding json_encode to the api call. $json = json_encode($twitter->get('apiurl')); Thank you so much for all your help!
0

After I had fixed your JSON (probably copy-paste errors) I have accessed the first (lowest branch) full_name by using:

$data = json_decode($json);
foreach($data->result->places as $item) {
  echo $item->name; // Mission Dolores, San Francisco
}

And the second element named full_name by using:

$data = json_decode($json);
foreach($data->result->places as $item) {
  foreach($item->contained_within as $cont) {
    echo $cont->full_name; // San Francisco, CA
  }
}

The philosophy behind parsing JSON is that some elements have one set of named element for a level, and the other has a number of recurring sets of elements. In this case there is a element called result -> places which can be more than one. And in there there is an element called contained_within which has more elements of its own. The correct way is looping over them using for/foreach but they can also be directly adressed:

$data = json_decode($json);
echo $data->result->places[0]->full_name; // Mission Dolores, San Francisco
echo $data->result->places[0]->contained_within[0]->full_name; // San Francisco, CA

1 Comment

Thank you so much for taking the time to help me out. I got it working
0

You need to decode your json first then do a foreach...you can try this

$json = json_decode("YOUR JSON HERE");
foreach ($json->result->places as $place) {
    echo $place->full_name;
}

1 Comment

Hey Rafael, you were on the money, I also had to first encode the api call
0

A quick guide to accessing items within a decoded JSON data structure:

Run your json through a validator/formatter so you can see the structure. I use this formatter as you can open and close the nodes to see the structure easily.

When you do json_decode($json_string), PHP's json decoder creates objects and (non-associative) arrays. To access data in objects, use the syntax $object->Attribute. To access data in arrays, give the index of the array item: $array[0] for the first item, $array[1] for the second item, etc.

Examples:

$data = json_decode($json);
echo "accuracy: " . $data->query->params->accuracy . "\n";
// output: "accuracy: 0"
echo "coord 1: " . $data->query->params->coordinates->coordinates[0] . "\n";
// output: "coord 1: -122.42284884"

foreach ($data->query->params->coordinates->coordinates as $c)
    echo "coord: " . $c . "\n"
// output: 
// coord: -122.42284884
// coord: 37.76893497

To get items deeper in the data structure, chain together these accessors. For example, to get full_name, you would use the following:

echo "Full name: " . $data->result->places[0]->full_name . "\n";
// output: Full name: Mission Dolores, San Francisco

1 Comment

Thank you so much for all the help, had to add json_encode to the api call but got it working thankfully!
0

Since you are looping from "places" already, the full_name property would be in $item->full_name already.

Same goes for the contained_within struct, $item->contained_within->full_name should work.

1 Comment

Thanks for the suggestion, just so you know json_encode and decode seemed to be the ticket.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.