How to extract a value from this JSON response - php

I am using the file_get_contents() function in PHP to retrieve the contents on a page containing a JSON response. However, I am struggling to get the "text" data.
$response = file_get_contents(someData)
I can use var_dump(json_decode($response)); to show the data, however, I am trying to get the data from the "text" field only within duration.
So far I have tried
$response[0];
$response->rows[0]->elements[0]->duration[0]->text;
But I cannot seem to get the data. I have pasted the response below
{
"destination_addresses" : [ "Manchester, UK", "Liverpool, Merseyside, UK" ],
"origin_addresses" : [ "London, UK" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "335 km",
"value" : 335444
},
"duration" : {
"text" : "3 hours 36 mins",
"value" : 12955
},
"status" : "OK"
},
{
"distance" : {
"text" : "354 km",
"value" : 354415
},
"duration" : {
"text" : "3 hours 43 mins",
"value" : 13387
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}

$response = json_decode(file_get_contents(someData));
$text = $response->rows[0]->elements[0]->duration->text;
var_dump($text);
Your only mistake was a [0] after duration.

Related

How to parse multi associative arrays to echo out by key values

Hey guys Im a student and my question might seem simple but i can't find the right answer anywhere. Please take a look. as you can see $parsed_json works fine with this code $parsed_json = $parsed_json['photos']; how do i add another key of the array there? i tried $parsed_json = $parsed_json[(['photos']['contactInfo'])]; but did now work. Any help will much appreciated. Thank you.
<?php
$json_string = file_get_contents("api/goes/here")
$parsed_json = json_decode($json_string, true);
print_r($parsed_json);
$parsed_json = $parsed_json[(['photos']['contactInfo'])];
foreach($parsed_json as $key => $value)
{
echo $value['typeName'] . '<br>';
echo $value['typeId'] . '<br>';
echo $value['familyName'] . '<br>';
// etc
?>
-------------JSON CONTENT------------------------------
{
"status" : 200,
"requestId" : "0ef05ee4-6bab-4488-a80c-04ce050ca074",
"likelihood" : 0.95,
"photos" : [ {
"type" : "linkedin",
"typeId" : "linkedin",
"typeName" : "LinkedIn",
"url" : "https://d2ojpxxtu63wzl.cloudfront.net/static/651f183b3a1bd463ef5298a2877f2c4f_0c027087db5cd03d244a7dd42e42fc969fa8d636bffd7635b46172c8a597aa73",
"isPrimary" : true
}, {
"type" : "twitter",
"typeId" : "twitter",
"typeName" : "Twitter",
"url" : "https://d2ojpxxtu63wzl.cloudfront.net/static/d0080f4ccd9ea21340b0fd994f82c0e0_2acdc7de41111f7d58e7544ed970b78e72f1739784417c146d5689d96ce79137"
} ],
"contactInfo" : {
"familyName" : "Cassini",
"fullName" : "Flavio Cassini",
"givenName" : "Flavio"
},
"organizations" : [ {
"name" : "DEVTECH .LLC",
"startDate" : "2015-03",
"title" : "President/Owner",
"current" : true
} ],
"demographics" : {
"locationDeduced" : {
"normalizedLocation" : "Boca Raton, United States",
"deducedLocation" : "Boca Raton, Florida, United States",
"city" : {
"name" : "Boca Raton"
},
"state" : {
"deduced" : true,
"name" : "Florida",
"code" : "FL"
},
"country" : {
"name" : "United States",
"code" : "US"
},
"continent" : {
"deduced" : true,
"name" : "North America"
},
"county" : {
"deduced" : true,
"name" : "Palm Beach"
},
"likelihood" : 1.0
},
"gender" : "Male",
"locationGeneral" : "Boca Raton, Florida, United States"
},
"socialProfiles" : [ {
"type" : "klout",
"typeId" : "klout",
"typeName" : "Klout",
"url" : "http://klout.com/DevTechServices",
"username" : "DevTechServices",
"id" : "91760869707035580"
}, {
"followers" : 67,
"following" : 67,
"type" : "linkedin",
"typeId" : "linkedin",
"typeName" : "LinkedIn",
"url" : "https://www.linkedin.com/in/devtechservices",
"username" : "devtechservices",
"id" : "428935547"
}, {
"bio" : "Student at Full Sail University",
"followers" : 5,
"following" : 36,
"type" : "twitter",
"typeId" : "twitter",
"typeName" : "Twitter",
"url" : "https://twitter.com/DevTechServices",
"username" : "DevTechServices",
"id" : "3245620291"
} ],
"digitalFootprint" : {
"scores" : [ {
"provider" : "klout",
"type" : "general",
"value" : 48
} ],
"topics" : [ {
"provider" : "klout",
"value" : "Bitcoin"
}, {
"provider" : "klout",
"value" : "Content Marketing"
}, {
"provider" : "klout",
"value" : "SAAS"
}, {
"provider" : "klout",
"value" : "Software"
}, {
"provider" : "klout",
"value" : "WordPress"
} ]
}
}
The short answer is that if $parsed_json represents an associative array of associative arrays, then it stands to reason that $parsed_json['photos'] is an associative array itself. To access the 'contactInfo' value inside it, you simply use $parsed_json['photos']['contactInfo'].

Parse JSONArray in Jquery

I am Creating a webapp where i could get the distance and time of travel using google map API..
https://maps.googleapis.com/maps/api/distancematrix/json?origins=10.964,76.007&destinations=10.982,75.999
I am using HTTP method as given by google..
Its returning JSON Format as give below
{
"destination_addresses" : [ "Kanyakumari - Panvel Highway, Palathara, Kerala 676501, India" ],
"origin_addresses" : [ "Kanyakumari - Panvel Highway, Randathani, Kerala 676510, India" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "2.5 km",
"value" : 2526
},
"duration" : {
"text" : "4 mins",
"value" : 228
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
How could i extract the distance text and duration text using jquery and alert it..
Use file_get_contents() and json_decode() the output..
$contents = file_get_contents('https://maps.googleapis.com/maps/api/distancematrix/json?origins=10.964,76.007&destinations=10.982,75.999');
$data = json_decode($contents,true);
echo 'Distance : '.$data['rows'][0]['elements'][0]['distance']['text'];
echo "<br>";
echo 'Duration : '.$data['rows'][0]['elements'][0]['duration']['text'];
This will give you :
Distance : 2.5 km
Duration : 4 mins

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.

parsing a specific JSON data

i am making a android application n use a .php file to call java script file that returns me a JSON output, now my problem is the output is in a valid JSON format, but i am confused as to how to parse the values. the output is
{
"destination_addresses" : [
"Kambarganvi road, Durgadakeri, Karnataka 580011, India",
"St Inez Road, Santa Inez, Panjim, Goa 403001, India",
"Dr Braganza Pereira Road, Santa Inez, Panjim, Goa 403001, India",
"Dayanand Bandodkar Marg, Santa Inez, Panjim, Goa 403001, India",
"St Inez Road, Santa Inez, Panjim, Goa 403001, India",
"18th June Road, Santa Inez, Panjim, Goa 403001, India"
],
"origin_addresses" : [ "Suyog Residency, St Joaquim Road, Borda, Margao, Goa 403602, India" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "133 km",
"value" : 132717
},
"duration" : {
"text" : "1 day 4 hours",
"value" : 100199
},
"status" : "OK"
},
{
"distance" : {
"text" : "33.4 km",
"value" : 33427
},
"duration" : {
"text" : "6 hours 54 mins",
"value" : 24832
},
"status" : "OK"
},
{
"distance" : {
"text" : "33.5 km",
"value" : 33518
},
"duration" : {
"text" : "6 hours 55 mins",
"value" : 24923
},
"status" : "OK"
},
{
"distance" : {
"text" : "33.8 km",
"value" : 33834
},
"duration" : {
"text" : "7 hours 0 mins",
"value" : 25170
},
"status" : "OK"
},
{
"distance" : {
"text" : "33.5 km",
"value" : 33503
},
"duration" : {
"text" : "6 hours 55 mins",
"value" : 24893
},
"status" : "OK"
},
{
"distance" : {
"text" : "33.5 km",
"value" : 33457
},
"duration" : {
"text" : "6 hours 55 mins",
"value" : 24880
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
i want to parse the values in such a way that i can place the distances of the result should be put in a data structure like an array and then sort them.
Thank you in advance.
use this to make own model .
http://www.jsonschema2pojo.org/
after making model you can use bwlow code.
Gson gson = new Gson();
gson.fromJson(jData, AddPostModel.class);
AddPostModel have all the data which comes from server.

How to get coordinates from the Query Autocomplete? [duplicate]

This question already has an answer here:
Places Autocomplete API to get GPS coordinates from address entered
(1 answer)
Closed 8 years ago.
Suppose a very simple function to query Query Autocomplete:
$query_google_places = function ($input, array $location = null) {
$parameters = ['key' => 'AIzaSyAjCY7qYiaMv8Kkk_-D1Ha7wlRkr5neppk', 'input' => $input, 'sensor' => 'false'];
if ($location) {
$parameters['location'] = $location['lat'] . ',' . $location['lng'];
$parameters['radius'] = 10000;
}
$url = 'https://maps.googleapis.com/maps/api/place/queryautocomplete/json?' . \http_build_query($parameters);
$response = file_get_contents($url);
return $response;
};
This returns:
{
"predictions" : [
{
"description" : "Pizza Hut, Halifax, United Kingdom",
"id" : "d9274717e1e203c41287fa5936701b9584814965",
"matched_substrings" : [
{
"length" : 9,
"offset" : 0
}
],
"reference" : "CmRaAAAAyulRkdspSJ2Mr5kmlhYOC-ZT7AsKdnnwjGkFFoGHNjMWwTS5mNvQBu6FqoQ89E4U0eC-PNGN0wPD8WEYgO1if6jMmxWAqkraDFOryC8B8cWTvX333l_0UaRv_sXBIITqEhCSrz9aQB0fch-AFDS3wKG7GhTRoQw09IODWJIorqjjwCYTktkfKw",
"terms" : [
{
"offset" : 0,
"value" : "Pizza Hut"
},
{
"offset" : 11,
"value" : "Halifax"
},
{
"offset" : 20,
"value" : "United Kingdom"
}
],
"types" : [ "establishment" ]
},
{
"description" : "Pizza Hut, John William Street, Huddersfield, United Kingdom",
"id" : "a1571b1434ac1491b5f6775d9a30f8ec7798a310",
"matched_substrings" : [
{
"length" : 9,
"offset" : 0
}
],
"reference" : "CoQBdAAAADaFqqtB9NGk_v1yZdY3m6OxILfLva556GBHxHIVdPHu_R0fQCm5kCduCjKL4BgiIdoNIejet3WI7xNanaiWDpiMD1Ml7Q9EnfhypReK0N6mQIY3TxOUcmf_INhkenU3ZVL8Vk9lAxqjq5ZfxiEZk9Vv8GaEnok_OJnaRBuZdCmtEhAYs-0Qc2Zza4fLuUXIiLknGhQogPaBcUm10Y59EA5i6BWPbTNXcA",
"terms" : [
{
"offset" : 0,
"value" : "Pizza Hut"
},
{
"offset" : 11,
"value" : "John William Street"
},
{
"offset" : 32,
"value" : "Huddersfield"
},
{
"offset" : 46,
"value" : "United Kingdom"
}
],
"types" : [ "establishment" ]
},
{
"description" : "pizza hut",
"matched_substrings" : [
{
"length" : 9,
"offset" : 0
}
],
"terms" : [
{
"offset" : 0,
"value" : "pizza hut"
}
]
},
{
"description" : "Pizza Hut Delivery, Wakefield Road, Huddersfield, United Kingdom",
"id" : "0c6830de14a8e23bf971626e880201f5290ec9a6",
"matched_substrings" : [
{
"length" : 9,
"offset" : 0
}
],
"reference" : "CoQBeQAAAJnMKHhJh-IE64z6seh3sbnm4dt0h1zbMYLr4BPGCITQTZLp4lkm12HKEFw0Bt761UaZPsESrY4ha7XSXusqqRVstmRFBF2wiwF5HGMO9DhRSeIzJ8CkNvsxmlqINosGBBPUHEDQEeSOoPHn3u3MeByoLVw6AzZ9N6eTrm94hsX9EhBB9cIoXjhHjR9Tr3zBROM7GhRhpYagW9qWs9hGZ3V0o9WXfrfcXw",
"terms" : [
{
"offset" : 0,
"value" : "Pizza Hut Delivery"
},
{
"offset" : 20,
"value" : "Wakefield Road"
},
{
"offset" : 36,
"value" : "Huddersfield"
},
{
"offset" : 50,
"value" : "United Kingdom"
}
],
"types" : [ "establishment" ]
},
{
"description" : "Pizza Hut Delivery, Westgate, Halifax, United Kingdom",
"id" : "667c14a2cb5bb676bd02911e924db82fb5cbe6df",
"matched_substrings" : [
{
"length" : 9,
"offset" : 0
}
],
"reference" : "CnRtAAAAEtMYQ9N4Gmn8dpZqzHOxYGPCNP9QQ6M-gHjj2hJv2euH4gUVvDhmgazi6LcRjdYpUF41moGLr26IGc2vOPfvFg_kHTqTIYHHwiD84bu0PeEzmLzIzJw2IkGNpcW1o6weO86TW8zaUaMFZ2zNW-tynhIQFT8GvSn_q7DAoP3ytM14ExoUN3sShljpfaCWEUknvsfAjZJ_Ru4",
"terms" : [
{
"offset" : 0,
"value" : "Pizza Hut Delivery"
},
{
"offset" : 20,
"value" : "Westgate"
},
{
"offset" : 30,
"value" : "Halifax"
},
{
"offset" : 39,
"value" : "United Kingdom"
}
],
"types" : [ "establishment" ]
}
],
"status" : "OK"
}
How do I get coordinates for each result? Note, that this is server-side question.
IMO, autocompletion or query autocompletion results live in a different world than search results. Google assumes you're not supposed to need coordinates in the autocompletion list because this is not the data you will be presenting on your map or in any controller. The data you'll present will be the result of a true "search" request.
Conclusion: you're supposed to call again Google server on endpoints such as nearby search, text search or details to get the coordinates.
If you want to use details, if the user clicked on a prediction from autocomplete for example, you'll use reference attribute as a parameter of your http request to identify the clicked prediction.

Categories