Suren Chemudugunta
Suren Chemudugunta

Reputation: 13

How to Properly Convert String to Associative Array in PHP

i want to convert this string to Proper associative array.

please click on the link to see string data.

https://maps.googleapis.com/maps/api/geocode/json?latlng=16.539311299999998,80.5820222

i want that to be converted into a proper Associaitve array.

im looking something like this.

echo $array['long_name'] should return a value like 'Attlee Road'

please help me with this, im trying this from 2 days, trying all explode, implode, foreachloops, im confused a lot, please someone help me with this.

Below code will echo the string data

<?php

$lat = 16.539311299999998;
$lng = 80.5820222;

$url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" . $lat . "," . $lng . ";

function get_data($url) {
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

$returned_contents = get_data($url);

echo "<pre>";
print_r($returned_contents);
echo "</pre>";

?>

Upvotes: 0

Views: 287

Answers (3)

Avinash Antala
Avinash Antala

Reputation: 671

Try it

<?php

$lat = 16.539311299999998;
$lng = 80.5820222;

$url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" . $lat . "," . $lng . "&key=AIzaSyDCgyjLTrpadabEAyDNXf2GPpgChvpMw_4";

function get_data($url) {
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

$returned_contents = get_data($url);
$returned_contents = json_decode($returned_contents);
echo "<pre>";
print_r($returned_contents);
echo "</pre>";

?>

Upvotes: 0

Mohammad Hamedani
Mohammad Hamedani

Reputation: 3354

You must be use json_decode() function.

<?php

$lat = 16.539311299999998;
$lng = 80.5820222;

$url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" . $lat . "," . $lng . "&key=AIzaSyDCgyjLTrpadabEAyDNXf2GPpgChvpMw_4";

function get_data($url) {
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

$returned_contents = get_data($url);

$returned_contents_array = json_decode($returned_contents, true);
$results = $returned_contents_array['results'];
foreach($results as $result) {
    echo $result['address_components'][0]['long_name'];
}

?>

Upvotes: 1

dEL
dEL

Reputation: 502

Use json_decode() on your output

Upvotes: 1

Related Questions