Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing Json response using PHP with space in array key

I have a response for a zip code API. However, I cannot figure out how to the the value from 'place name' because of the space between the two words. No quite sure where to go from here.

object(stdClass)#1 (4) {
 ["post code"]=>
 string(5) "42223"
 ["country"]=>
 string(13) "United States"
 ["country abbreviation"]=>
 string(2) "US"
 ["places"]=>
 array(1) {
   [0]=>
   object(stdClass)#2 (5) {
     ["place name"]=>
     string(13) "Fort Campbell"
     ["longitude"]=>
     string(8) "-87.5585"
     ["state"]=>
     string(8) "Kentucky"
     ["state abbreviation"]=>
     string(2) "KY"
     ["latitude"]=>
     string(7) "36.5995"
   }
 }
}
like image 840
smack-a-bro Avatar asked Dec 02 '22 18:12

smack-a-bro


1 Answers

You need to put them inside a curly brace with a single quote:

$place_name = $response->places[0]->{'place name'};
echo $place_name;

Or as @scragar said in the comments, if you're not confortable accessing them thru objects, you can put a true flag on json_decode($response, true), so that you can access them as associative arrays instead.

like image 150
Kevin Avatar answered Dec 06 '22 11:12

Kevin