php parse json data from google directions - php

I'm trying to parse json data from google directions but can't seem to access access any of the values. Here is the php code;
$url = "http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles&sensor=false";
$jsonfile = json_encode(file_get_contents($url));
$jsondata = json_decode($jsonfile);
echo $jsondata->distance;
here is (some) of the json data returns:
{ "routes" : [ { "bounds" : { "northeast" : { "lat" : 41.90085000000001, "lng" : -87.62979000000001 }, "southwest" : { "lat" : 34.052360, "lng" : -118.243560 } }, "copyrights" : "Map data ©2012 Google", "legs" : [ { "distance" : { "text" : "2,015 mi", "value" : 3243390 }, "duration" : { "text" : "1 day 8 hours", "value" : 114318 }, "end_address" : "Los Angeles, CA, USA", "end_location" : { "lat" : 34.052360, "lng" : -118.243560 }, "start_address" : "Chicago, IL, USA", "start_location" : { "lat" : 41.87811000000001, "lng" : -87.62979000000001 }, "steps" : [ { "distance" : { "text" : "0.2 mi", "value" : 269 }, "duration" : { "text" : "1 min", "value" : 34 }, "end_location" : { "lat" : 41.87570, "lng" : -87.62969000000001 }, "html_instructions" : "Head \u003cb\u003esouth\u003c/b\u003e on \u003cb\u003eS Federal St\u003c/b\u003e toward \u003cb\u003eW Van Buren St\u003c/b\u003e", "polyline" : { "points" : "eir~FdezuOhFIF?HAdFG" }, "start_location" : { "lat" : 41.87811000000001, "lng" : -87.62979000000001 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "0.2 mi", "value" : 328 }, "duration" : { "text" : "1 min", "value" : 51 }, "end_location" : { "lat" : 41.875680, "lng" : -87.63366000000002 }, "html_instructions" : "Turn \u003cb\u003eright\u003c/b\u003e onto \u003cb\u003eW Congress Pkwy\u003c/b\u003e", "polyline" : { "points" : "czq~FpdzuO?jE#nEBfGAtB" }, "start_location" : { "lat" : 41.87570, "lng" : -87.62969000000001 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "14.0 mi", "value" : 22564 }, "duration" : { "text" : "17 mins", "value" : 1031 }, "end_location" : { "lat" : 41.873870, "lng" : -87.903170 }, "html_instructions" : "Continue onto \u003cb\u003eI-290 W\u003c/b\u003e", "polyline" : { "points" : "_zq~Fj}zuOCtD?fA?f#?pC?P?T#V#zJ?##T?J?J?F?N?#?J?J?N?p##xA?h#?B?~A#xD?h#?lB?n##n#?n#?B#~G?f#A\\EvAGnBEz#EpA?JBlC?F?F?T?B?f#HtM?R?J?t#?|CCvDAb#E`EGlDKzCCd#OrBa#rFGfAAd#?HAp#?`ADbJDzJ?fB?dENdFB~N?d#?RFlH#~C?J#~A?H?XFrKAx##l#?n##^#bANnQ?rAAnMCnC#tH#x#FxJ?hB#tM?j#?p#BxFLrT?B?H?jQBbG#|AHxLBVJ~CLfC\\|EHtAHtAVpDf#tF\\dFTxCXhDVzBNtCFlEB|HBvEDlRAhC?xANxU#^?~A?nADxW#vA?l#Dv[?|#?\\#bCHdI#z#ZxDh#zDRx#T|#t#dCPf#bBlEf#dB^vA^jCR`CDv#?LHfBH`X?z#F|V#pF?`#L|Y#v##dKDbO?jEDdHZjHR`EBd#D`#h#~IHpB#p##n#?p#BjACvFE`IMrIQzIKfEc#tQEjCCn#}#dUSjFCf#mA~[Ar#QlMObGWlEEx#sB`_#Ep#aBt\\EdA?FcAbU?XCrCKnC?zBR|LB`#B\\?Dz#hG#F#Ft#vDJl#pBfMnAtHZ|ERrEJhTH|GLvJ^rHr#|HX`G#`FLnX#`B?`A#|CAbCRnT?BJ`OHrJDbC#r#XzZ?#DfHMdIe#bHIhD#zHPhP?##V#fBN|O?T#j#DnEHpQFlGDtCDtEDrEFlEt#jJF~#`#dDPtAXtCd#`IFlC#j#?j#?hAHpLB~C#bDA|DErBCl#Av#O`C]~DWzB[lB[fB]zAo#dCc#~Am#jBo#bBoCxG?#Sd#g#vAY~#St#W|#_#bBUhAYdB]vBMhA[vCKtAEbAIxA?PAXCb#AhA" }, "start_location" : { "lat" : 41.875680, "lng" : -87.63366000000002 }, "travel_mode" : "DRIVING" }, { "distance" : { "text" : "140 mi", "value" : 224957 }, "duration" : { "text" : "2 hours 13 mins", "value" : 8008 }, "end_location" : { "lat" : 41.53651000000001, "lng" : -90.32902000000001 }
The error returned is as follows:
( ! ) Notice: Trying to get property of non-object in C:\wamp2\www\phpAcademy\GoogleDirectionsApi\TMP25mnfz82oi.php on line 8
Call Stack
# Time Memory Function Location
1 0.0004 366752 {main}( ) ..\TMP25mnfz82oi.php:0

Google already returns JSON, so you do not need to encode it first. Secondly the 'distance' key is deeper in the response structure:
$origin = "Rome, Italy";
$destination = "Venice, Italy";
$key = "YOUR-OWN-KEY";
$url = "https://maps.googleapis.com/maps/api/directions/json?origin=".urlencode($origin).",IL&destination=" . urlencode( $destination) . "&sensor=false&key=" . $key;
$jsonfile = file_get_contents($url);
$jsondata = json_decode($jsonfile);
echo $jsondata->routes[0]->legs[0]->distance;

You can easily get all the data in json or array format:
$url = "https://maps.googleapis.com/maps/api/directions/json?origin=28.704059,77.102490&destination=30.719059,76.748704&sensor=false";
$jsonfile = file_get_contents($url);
$jsondata = json_decode($jsonfile);
echo $jsondata->routes[0]->legs[0]->distance;
if this error occur:
Catchable fatal error: Object of class stdClass could not be converted to string
than plz use for a output print_r() function

Related

How to parse Google Directions API Json in PHP, specifically the Distance-Values and Duration-Values for each "Step" and "Leg" which are all nested?

The json response can have any number of Distance-Values, Duration-Values, Steps and Legs nested within each other. I need to ensure the original pairing of Distance and Duration in a variable for later math. Note the file also has Distance-Values and Duration-Values NOT nested within the Steps that I am not interested in collecting. I am a newbie PHP programmer - please be gentle. Thank you.
Here is a sample json file response, apologies it is so long.
{
"geocoded_waypoints" : [
{
"geocoder_status" : "OK",
"partial_match" : true,
"place_id" : "ChIJq0F7QdOGwokRtGWVrOp28h0",
"types" : [ "premise" ]
},
{
"geocoder_status" : "OK",
"partial_match" : true,
"place_id" : "ChIJvzh05jM_6IkRhcy9aqUcTHM",
"types" : [ "establishment", "point_of_interest", "university" ]
},
{
"geocoder_status" : "OK",
"partial_match" : true,
"place_id" : "ChIJ28a23cMv6IkRLzOqZ0h6vwo",
"types" : [ "premise" ]
}
],
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 40.9003613,
"lng" : -73.11792029999999
},
"southwest" : {
"lat" : 40.7791055,
"lng" : -73.5611243
}
},
"copyrights" : "Map data ©2020 Google",
"legs" : [
{
"distance" : {
"text" : "28.7 mi",
"value" : 46179
},
"duration" : {
"text" : "40 mins",
"value" : 2424
},
"end_address" : "100 Nicolls Rd, Stony Brook, NY 11794, USA",
"end_location" : {
"lat" : 40.9003613,
"lng" : -73.1305969
},
"start_address" : "99 Jericho Turnpike, Westbury, NY 11590, USA",
"start_location" : {
"lat" : 40.7791055,
"lng" : -73.56088389999999
},
"steps" : [
{
"distance" : {
"text" : "128 ft",
"value" : 39
},
"duration" : {
"text" : "1 min",
"value" : 14
},
"end_location" : {
"lat" : 40.7794066,
"lng" : -73.5611243
},
"html_instructions" : "Head \u003cb\u003enorthwest\u003c/b\u003e toward \u003cb\u003eJericho Turnpike\u003c/b\u003e",
"polyline" : {
"points" : "mt{wFnj~_M{#n#"
},
"start_location" : {
"lat" : 40.7791055,
"lng" : -73.56088389999999
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "0.4 mi",
"value" : 629
},
"duration" : {
"text" : "3 mins",
"value" : 158
},
"end_location" : {
"lat" : 40.7821022,
"lng" : -73.5545772
},
"html_instructions" : "Turn \u003cb\u003eright\u003c/b\u003e onto \u003cb\u003eJericho Turnpike\u003c/b\u003e",
"maneuver" : "turn-right",
"polyline" : {
"points" : "iv{wF~k~_Me#oAg#wAQe#M_#]_Ag#sAQe#g#wA[s#K[a#eAWu#Qs#I[m#gCi#{BAEk#{Bg#yB"
},
"start_location" : {
"lat" : 40.7794066,
"lng" : -73.5611243
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "0.2 mi",
"value" : 251
},
"duration" : {
"text" : "1 min",
"value" : 15
},
"end_location" : {
"lat" : 40.7827402,
"lng" : -73.55172809999999
},
"html_instructions" : "Slight \u003cb\u003eright\u003c/b\u003e onto \u003cb\u003eS Marginal Rd\u003c/b\u003e",
"maneuver" : "turn-slight-right",
"polyline" : {
"points" : "cg|wFbc}_MEe#AGAECKIc#I_#IYEY[mBKy#Ik#Ge#E_#EYAYCYAY"
},
"start_location" : {
"lat" : 40.7821022,
"lng" : -73.5545772
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "0.1 mi",
"value" : 218
},
"duration" : {
"text" : "1 min",
"value" : 13
},
"end_location" : {
"lat" : 40.7831579,
"lng" : -73.54922080000001
},
"html_instructions" : "Take the \u003cb\u003eInterstate 495 E\u003c/b\u003e ramp on the \u003cb\u003eleft\u003c/b\u003e to \u003cb\u003eRiverhead\u003c/b\u003e",
"maneuver" : "ramp-left",
"polyline" : {
"points" : "ck|wFhq|_MIYAEAICMASAMKeAKuAC]Cm#AAAYCi#Cs#AK?GAIAGACCEEI"
},
"start_location" : {
"lat" : 40.7827402,
"lng" : -73.55172809999999
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "1.3 mi",
"value" : 2154
},
"duration" : {
"text" : "1 min",
"value" : 83
},
"end_location" : {
"lat" : 40.7877687,
"lng" : -73.5245628
},
"html_instructions" : "Merge onto \u003cb\u003eI-495 E\u003c/b\u003e",
"maneuver" : "merge",
"polyline" : {
"points" : "wm|wFra|_MW{MWeIEq#]eIWeFOcCG{#UmD_#cFU}BQaBQaBQeBuAsMc#iDGe#Gi#c#}Cg#mDg#cD[mBc#kCYgB]mBa#cC_#kBi#eC[kA[mAa#yAOg#Wy#Qi#]eA"
},
"start_location" : {
"lat" : 40.7831579,
"lng" : -73.54922080000001
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "0.4 mi",
"value" : 679
},
"duration" : {
"text" : "1 min",
"value" : 34
},
"end_location" : {
"lat" : 40.79059609999999,
"lng" : -73.5181288
},
"html_instructions" : "Take exit \u003cb\u003e42\u003c/b\u003e for \u003cb\u003eBroadway\u003c/b\u003e/\u003cwbr/\u003e\u003cb\u003eNorthern Pkwy E\u003c/b\u003e toward \u003cb\u003eHauppauge\u003c/b\u003e",
"maneuver" : "ramp-right",
"polyline" : {
"points" : "qj}wFngw_MAa#AGK[OIOGMEMOC"
},
"start_location" : {
"lat" : 40.7877687,
"lng" : -73.5245628
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "16.0 mi",
"value" : 25810
},
"duration" : {
"text" : "16 mins",
"value" : 945
},
"end_location" : {
"lat" : 40.829462,
"lng" : -73.25121489999999
},
"html_instructions" : "Merge onto \u003cb\u003eNorthern State Pkwy\u003c/b\u003e",
"maneuver" : "merge",
"polyline" : {
"points" : "g|}wFh_v_Me#wAK[a#]#[#[#]#YBWBU#W#CB]DYD_#NaB"
},
"start_location" : {
"lat" : 40.79059609999999,
"lng" : -73.5181288
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "0.3 mi",
"value" : 463
},
"duration" : {
"text" : "1 min",
"value" : 18
},
"end_location" : {
"lat" : 40.8278228,
"lng" : -73.2461648
},
"html_instructions" : "Merge onto \u003cb\u003eNY-347\u003c/b\u003e/\u003cwbr/\u003e\u003cb\u003eNY-454 E\u003c/b\u003e",
"maneuver" : "merge",
"polyline" : {
"points" : "coexF`{a~LBQBOF_#H_#F[Ha#H_#Ji#Je#H_#XmA\\oAVkA~CwM"
},
"start_location" : {
"lat" : 40.829462,
"lng" : -73.25121489999999
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "1.8 mi",
"value" : 2820
},
"duration" : {
"text" : "3 mins",
"value" : 163
},
"end_location" : {
"lat" : 40.8243168,
"lng" : -73.21340239999999
},
"html_instructions" : "Continue straight to stay on \u003cb\u003eNY-347\u003c/b\u003e/\u003cwbr/\u003e\u003cb\u003eNY-454 E\u003c/b\u003e",
"maneuver" : "straight",
"polyline" : {
"points" : "{dexFn{`~L^_Bf#aCLi#b#{BlAyF^kB`#kBFWTeAd#gC`#gCN{#l#cF?IJcAPcCNoB`#eFTwCFcAXkD#[Dq#|#aMB[XiDVkDDw#NiCJyCHgD#gA#qA?c#?uAA[AqA?WC}#K{DEqAGmCAc#CqAGkBMcFA_#E_ACaACaAIoBA]A}A?qB?Y#oDH_EDkBVsDJsA"
},
"start_location" : {
"lat" : 40.8278228,
"lng" : -73.2461648
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "6.2 mi",
"value" : 9936
},
"duration" : {
"text" : "11 mins",
"value" : 689
},
"end_location" : {
"lat" : 40.8747687,
"lng" : -73.12067499999999
},
"html_instructions" : "Keep \u003cb\u003eleft\u003c/b\u003e to continue on \u003cb\u003eNY-347 E\u003c/b\u003e, follow signs for \u003cb\u003ePort Jefferson\u003c/b\u003e\u003cdiv style=\"font-size:0.9em\"\u003ePass by Carvel (on the right)\u003c/div\u003e",
"maneuver" : "keep-left",
"polyline" : {
"points" : "_odxFvnz}LFaD#o#Iw[q#yAeD_AqBk#oA{#mBoBmEc#cAoDwHQ_#"
},
"start_location" : {
"lat" : 40.8243168,
"lng" : -73.21340239999999
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "0.2 mi",
"value" : 281
},
"duration" : {
"text" : "1 min",
"value" : 34
},
"end_location" : {
"lat" : 40.8763118,
"lng" : -73.1180346
},
"html_instructions" : "Continue onto \u003cb\u003eSmithtown Bypass\u003c/b\u003e",
"polyline" : {
"points" : "ijnxFdkh}LcAuBQ]eCyEo#wAg#iA"
},
"start_location" : {
"lat" : 40.8747687,
"lng" : -73.12067499999999
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "1.8 mi",
"value" : 2899
},
"duration" : {
"text" : "4 mins",
"value" : 258
},
"end_location" : {
"lat" : 40.9003613,
"lng" : -73.1305969
},
"html_instructions" : "Turn \u003cb\u003eleft\u003c/b\u003e onto \u003cb\u003eStony Brook Rd\u003c/b\u003e\u003cdiv style=\"font-size:0.9em\"\u003eDestination will be on the right\u003c/div\u003e",
"maneuver" : "turn-left",
"polyline" : {
"points" : "}snxFtzg}LIU]TmBx#WJo#XiAd#IDqB|#sAj#sF`CoFzBaHvCmF|BaDrAw#`#wDbBiAt#gBpAMNo#d#_#TiBpAcAt#cCbB]VUN}BxAUNe#VoAp#aCnAcDdBiAl#}Ax#MHi#Tc#PkA\\wCv#yA`#{Ab#qAZqAVkCf#_BZWFiB\\uAXiB`#e#JeB\\[HMBSFA?WJ_#Tc#ZML"
},
"start_location" : {
"lat" : 40.8763118,
"lng" : -73.1180346
},
"travel_mode" : "DRIVING"
}
],
"traffic_speed_entry" : [],
"via_waypoint" : []
},
{
"distance" : {
"text" : "13.7 mi",
"value" : 21984
},
"duration" : {
"text" : "25 mins",
"value" : 1473
},
"end_address" : "18 Hauppauge Rd, Commack, NY 11725, USA",
"end_location" : {
"lat" : 40.8286064,
"lng" : -73.2937987
},
"start_address" : "100 Nicolls Rd, Stony Brook, NY 11794, USA",
"start_location" : {
"lat" : 40.9003613,
"lng" : -73.1305969
},
"steps" : [
{
"distance" : {
"text" : "1.8 mi",
"value" : 2870
},
"duration" : {
"text" : "4 mins",
"value" : 258
},
"end_location" : {
"lat" : 40.87645940000001,
"lng" : -73.1181333
},
"html_instructions" : "Head \u003cb\u003esoutheast\u003c/b\u003e on \u003cb\u003eStony Brook Rd\u003c/b\u003e toward \u003cb\u003eDevelopment Drive\u003c/b\u003e",
"polyline" : {
"points" : "gjsxFfij}LLMb#[^UVK#?RGLCZIdB]d#KhBa#tAYhB]VG~A[jCg#pAWpA[zAc#xAa#vCw#jA]b#Qh#ULI|Ay#hAm#bDeB`CoAnAq#d#WTO|ByATO\\WbCcBbAu#hBqA^Un#e#VK`BiAjAq#tDaBx#_#nAg#pAi#lF}BpEmBpAk#nF{BrF_C`Bs#jBy#pAi#`Ac#nB{#"
},
"start_location" : {
"lat" : 40.9003613,
"lng" : -73.1305969
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "3.6 mi",
"value" : 5810
},
"duration" : {
"text" : "8 mins",
"value" : 456
},
"end_location" : {
"lat" : 40.8469852,
"lng" : -73.17149669999999
},
"html_instructions" : "Turn \u003cb\u003eright\u003c/b\u003e onto \u003cb\u003eNY-347 W\u003c/b\u003e/\u003cwbr/\u003e\u003cb\u003eSmithtown Bypass\u003c/b\u003e",
"maneuver" : "turn-right",
"polyline" : {
"points" : "{tnxFh{g}LhD~Gp#tCh#xA~#|B"
},
"start_location" : {
"lat" : 40.87645940000001,
"lng" : -73.1181333
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "4.6 mi",
"value" : 7390
},
"duration" : {
"text" : "7 mins",
"value" : 430
},
"end_location" : {
"lat" : 40.8288007,
"lng" : -73.2481703
},
"html_instructions" : "Continue straight to stay on \u003cb\u003eNY-347 W\u003c/b\u003e/\u003cwbr/\u003e\u003cb\u003eSmithtown Bypass\u003c/b\u003e",
"maneuver" : "straight",
"polyline" : {
"points" : "u|hxFzhr}Lj#fA|EVQv#sAjGs#|CS~#WbA"
},
"start_location" : {
"lat" : 40.8469852,
"lng" : -73.17149669999999
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "2.9 mi",
"value" : 4593
},
"duration" : {
"text" : "3 mins",
"value" : 177
},
"end_location" : {
"lat" : 40.8186598,
"lng" : -73.2952425
},
"html_instructions" : "Keep \u003cb\u003eleft\u003c/b\u003e to continue on \u003cb\u003eNorthern State Pkwy\u003c/b\u003e",
"maneuver" : "keep-left",
"polyline" : {
"points" : "_kexF`ha~L[pE`BI`D"
},
"start_location" : {
"lat" : 40.8288007,
"lng" : -73.2481703
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "0.1 mi",
"value" : 176
},
"duration" : {
"text" : "1 min",
"value" : 21
},
"end_location" : {
"lat" : 40.8195393,
"lng" : -73.29465789999999
},
"html_instructions" : "Take exit \u003cb\u003e43\u003c/b\u003e for \u003cb\u003eSuffolk County 4\u003c/b\u003e toward \u003cb\u003eCommack\u003c/b\u003e",
"maneuver" : "ramp-right",
"polyline" : {
"points" : "skcxFfnj~LMb#ADADADABABCBABCBGDABC#GBC#E?C#A?A?C?C?C?AAE?CACAECECGECCAECCACCICICOCUOkAIe#"
},
"start_location" : {
"lat" : 40.8186598,
"lng" : -73.2952425
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "299 ft",
"value" : 91
},
"duration" : {
"text" : "1 min",
"value" : 19
},
"end_location" : {
"lat" : 40.8197276,
"lng" : -73.29361089999999
},
"html_instructions" : "Keep \u003cb\u003eleft\u003c/b\u003e at the fork, follow signs for \u003cb\u003eCounty Road 4 N\u003c/b\u003e",
"maneuver" : "fork-left",
"polyline" : {
"points" : "cqcxFrjj~LQ{AOyAC["
},
"start_location" : {
"lat" : 40.8195393,
"lng" : -73.29465789999999
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "0.6 mi",
"value" : 997
},
"duration" : {
"text" : "2 mins",
"value" : 92
},
"end_location" : {
"lat" : 40.82857569999999,
"lng" : -73.29312469999999
},
"html_instructions" : "Turn \u003cb\u003eleft\u003c/b\u003e onto \u003cb\u003eCommack Rd\u003c/b\u003e",
"maneuver" : "turn-left",
"polyline" : {
"points" : "ircxF`dj~L?IAQKA{#CE?cAA_AC_AC_#CqEMw#Cw#A_BAYFWAQ?cCGsDK{FOsCIs#A[#Q?gA#E#k#BU#U#"
},
"start_location" : {
"lat" : 40.8197276,
"lng" : -73.29361089999999
},
"travel_mode" : "DRIVING"
},
{
"distance" : {
"text" : "187 ft",
"value" : 57
},
"duration" : {
"text" : "1 min",
"value" : 20
},
"end_location" : {
"lat" : 40.8286064,
"lng" : -73.2937987
},
"html_instructions" : "Turn \u003cb\u003eleft\u003c/b\u003e onto \u003cb\u003eHauppauge Rd\u003c/b\u003e\u003cdiv style=\"font-size:0.9em\"\u003eDestination will be on the right\u003c/div\u003e",
"maneuver" : "turn-left",
"polyline" : {
"points" : "siexF~`j~LAp#An#Ad#"
},
"start_location" : {
"lat" : 40.82857569999999,
"lng" : -73.29312469999999
},
"travel_mode" : "DRIVING"
}
],
"traffic_speed_entry" : [],
"via_waypoint" : []
}
],
"overview_polyline" : {
"points" : "mt{wFnj~_M{#n#e#oAy#tA"
},
"summary" : "Northern State Pkwy and NY-347",
"warnings" : [],
"waypoint_order" : [ 0 ]
}
],
"status" : "OK"
}
I figured this out by using multiple nested "foreach" loops with several "if" tests. I'm sure it's not the most elegant but it works. The key (pun intended) was keeping track of all the index/keys for each nested foreach loop.

Trying to access an element in an array that is in an array

I'm currently working with google places api and it returns the json in the quote. I'm trying to access the "photo_reference" element in the "photos" array and I've been using the attached code but it keeps returning null and I can't figure out why($response is where I stored my json).
$response["results"][1]["photos"]["photo_reference"];
"results" : [
{
"formatted_address" : "525 W 28th St, Los Angeles, CA 90007, USA",
"geometry" : {
"location" : {
"lat" : 34.0265698,
"lng" : -118.2766572
},
"viewport" : {
"northeast" : {
"lat" : 34.02787052989272,
"lng" : -118.2752304701073
},
"southwest" : {
"lat" : 34.02517087010728,
"lng" : -118.2779301298927
}
}
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
"id" : "73f56efe009cf4f46fab07e380e89fb1024f2dda",
"name" : "Grinder",
"opening_hours" : {
"open_now" : true
},
"photos" : [
{
"height" : 1080,
"html_attributions" : [
"\u003ca href=\"https://maps.google.com/maps/contrib/111289966799928187791/photos\"\u003eRomeo C\u003c/a\u003e"
],
"photo_reference" : "CmRaAAAAYZeA7hp-fV6SUytgcjrEbTeOTDarmxhYYUoOUixAKCMhsJGyQdSnTl_LYmBGfcGjH44BfLmDJDV325flXgjCMHa8WCsKFBciYUT6hYUG0YesO5FxkClNpSDH-gPjOj5kEhBYB8hWZbWG-o20qvN9mfwiGhROzzx8GZWVS17R5NOBx7ZiJUTEug",
"width" : 1920
}
],
"place_id" : "ChIJGZfInOfHwoARtMA9n87JMK8",
"plus_code" : {
"compound_code" : "2PGF+J8 Los Angeles, California, USA",
"global_code" : "85632PGF+J8"
},
"price_level" : 1,
"rating" : 4.3,
"reference" : "ChIJGZfInOfHwoARtMA9n87JMK8",
"types" : [ "restaurant", "point_of_interest", "food", "establishment" ],
"user_ratings_total" : 645
},
As ["photos"] has a sub array you need to use...
$response["results"][0]["photos"][0]["photo_reference"]
It's always worth using print_r() and following the structure through to work out where the various arrays sit.

How to print the Google Distance Matrix Results Json Data

How to print the Results from Google Distance matrix iam Getting a results like this:
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "4,8 km",
"value" : 4820
},
"duration" : {
"text" : "17 minutes",
"value" : 1038
},
"status" : "OK"
},
{
"distance" : {
"text" : "11,1 km",
"value" : 11064
},
"duration" : {
"text" : "25 minutes",
"value" : 1506
},
"status" : "OK"
}
]
}
],
And My Php Code to print The Output is
$json = file_get_contents($url);
$result = json_decode($json, true);
for($i=0; $i<count($result['rows']); $i++) {
echo "Kilometers " . $result['rows'][$i]["elements"][$i]['distance']['text'];
}
.Please Help
Given that you haven't included all the response, the method invlolved in the retrieval of the data nor the final desired output it is tricky to answer but I hope the following will give guidance on how to render the output.
This uses example data from the interwebs rather than the partial example code given in the question - a bit rough perhaps but...
$res='{
"destination_addresses" : [
"Commons Way, Bridgewater, NJ 08807, USA",
"Morris Turnpike, Short Hills, NJ 07078, USA",
"Monmouth Mall, Eatontown, NJ 07724, USA",
"Garden State Plaza Blvd, Paramus, NJ 07652, USA",
"Newport Centre Mall, Jersey City, NJ 07302, USA"
],
"origin_addresses" : [ "75 Ninth Ave, New York, NY 10011, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "68.8 km",
"value" : 68781
},
"duration" : {
"text" : "56 mins",
"value" : 3334
},
"duration_in_traffic" : {
"text" : "1 hour 1 min",
"value" : 3687
},
"status" : "OK"
},
{
"distance" : {
"text" : "34.8 km",
"value" : 34806
},
"duration" : {
"text" : "36 mins",
"value" : 2138
},
"duration_in_traffic" : {
"text" : "41 mins",
"value" : 2487
},
"status" : "OK"
},
{
"distance" : {
"text" : "86.3 km",
"value" : 86322
},
"duration" : {
"text" : "1 hour 6 mins",
"value" : 3930
},
"duration_in_traffic" : {
"text" : "1 hour 7 mins",
"value" : 4044
},
"status" : "OK"
},
{
"distance" : {
"text" : "32.3 km",
"value" : 32278
},
"duration" : {
"text" : "33 mins",
"value" : 2009
},
"duration_in_traffic" : {
"text" : "35 mins",
"value" : 2082
},
"status" : "OK"
},
{
"distance" : {
"text" : "6.9 km",
"value" : 6879
},
"duration" : {
"text" : "19 mins",
"value" : 1113
},
"duration_in_traffic" : {
"text" : "24 mins",
"value" : 1444
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}';
/* return as an object for easier notation */
$json=json_decode( $res, false );
$origins = $json->origin_addresses;
$destinations=$json->destination_addresses;
/* if there are multiple rows, use a loop and `$rows[$i]` etc */
$elements=$json->rows[0]->elements;
foreach( $elements as $i => $obj ){
echo '
<div>
<h5>From: '.$origins[ 0 ].' to '.$destinations[ $i ].'</h5>
Distance: '.$obj->distance->text.',
Duration:'.$obj->duration->text.',
In traffic: '.$obj->duration_in_traffic->text.',
Status: '.$obj->status.'
</div>';
}
Here is an example using a nested foreach, this is not the only way to render the output but it works.
$json = file_get_contents($url);
$result = json_decode($json, true);
foreach ($result['rows'][0] as $elements => $element) {
foreach ($element as $key => $value) {
echo $value['distance']['text'];
echo $value['duration']['text'];
echo $value['status'];
echo '<br>';
}
}
All we are doing is accessing a multi-dimensional array using $key => $value and then $value[$key] notation... I would suggest a crash course on how to handle arrays in php, this one is great: https://www.youtube.com/watch?v=57y5maglayQ
You can also look at the overall structure of your array by writing echo '<pre>', var_dump($result), '</pre>;' which will show your array => key pairs.

Parse json string in php

{
"results" : [
{
"address_components" : [
{
"long_name" : "New Delhi",
"short_name" : "New Delhi",
"types" : [ "locality", "political" ]
},
{
"long_name" : "West Delhi",
"short_name" : "West Delhi",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Delhi",
"short_name" : "DL",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "India",
"short_name" : "IN",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "New Delhi, Delhi, India",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 28.88981589999999,
"lng" : 77.34181459999999
},
"southwest" : {
"lat" : 28.4010669,
"lng" : 76.8396999
}
},
"location" : {
"lat" : 28.635308,
"lng" : 77.22496
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 28.88981589999999,
"lng" : 77.34181459999999
},
"southwest" : {
"lat" : 28.4010669,
"lng" : 76.8396999
}
}
},
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
How do i parse the above json string with php
Trying the following code out but no success:
$url = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?address=Delhi&sensor=true");
$json = json_decode($url);
foreach($json->results as $item) {
$location_item = array(
'address' => $item->formatted_address,
);
}
I am getting blank page the code doesn't work please help i am new to php
I am getting blank page the code doesn't work please help i am new to
php
Your code actually works , maybe you are not printing the data that is why you are getting a blank page.
Tested
<?php
$url = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?address=Delhi&sensor=true");
$json = json_decode($url);
foreach($json->results as $item) {
$location_item = array(
'address' => $item->formatted_address,
);
}
print_r($location_item);
OUTPUT :
Array
(
[address] => New Delhi, Delhi, India
)

Accessing a json file in php

I have a json file like this:
{"results" : [
{
"address_components" : [
{
"long_name" : "4400",
"short_name" : "4400",
"types" : [ "postal_code" ]
},
{
"long_name" : "Upper Austria",
"short_name" : "OÖ",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "Austria",
"short_name" : "AT",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "4400, Austria",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 48.06669549999999,
"lng" : 14.4687485
},
"southwest" : {
"lat" : 47.9987654,
"lng" : 14.3408425
}
},
"location" : {
"lat" : 48.0418838,
"lng" : 14.4078882
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 48.06669549999999,
"lng" : 14.4687485
},
"southwest" : {
"lat" : 47.9987654,
"lng" : 14.3408425
}
}
},
"types" : [ "postal_code" ]
}
],
"status" : "OK"
}
and everytime i try to access it i get undefined index location, i want to access this part:
"location" : {
"lat" : 48.0418838,
"lng" : 14.4078882
},
with this:
$url1="http://maps.googleapis.com/maps/api/geocode/json?address=AT-".$a."&sensor=false";
$unparsed_json = file_get_contents($url1);
$data =(array) json_decode($unparsed_json);
echo $unparsed_json;
$latlng= $data['results']['location']['lat'];
echo $latlng;
but everything I try gives result null. Any help would be really appreciated.
You are using arrays in your json code and need to reference items accordingly, also your location is located in the geometry entity.
Try out with this $latlng= $data['results'][0]['geometry']['location']['lat'];
Here's even a demo in JS just to show the concept. Use the line above in your PHP code.

Categories