1

I am using an api to detect the user's location using the ip address. For this, instead of using file_get_contents, I want to use the cURL function I wrote below. But the string I got is very complex. How can I convert this string to a legible array?

My Code

function curl_get_contents($url) {
    // Initiate the curl session
    $ch = curl_init();
    // Set the URL
    curl_setopt($ch, CURLOPT_URL, $url);
    // Removes the headers from the output
    curl_setopt($ch, CURLOPT_HEADER, 0);
    // Return the output instead of displaying it directly
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // Execute the curl session
    $output = curl_exec($ch);
    // Close the curl session
    curl_close($ch);
    // Return the output as a variable
    return $output;
}

$output = curl_get_contents("http://ip-api.com/php/".$ip);

echo $output;

result

a:14:{s:6:"status";s:7:"success";s:7:"country";s:6:"Turkey";s:11:"countryCode";s:2:"TR";s:6:"region";s:2:"35";s:10:"regionName";s:5:"Izmir";s:4:"city";s:5:"Izmir";s:3:"zip";s:5:"35600";s:3:"lat";d:38.4667;s:3:"lon";d:27.1333;s:8:"timezone";s:15:"Europe/Istanbul";s:3:"isp";s:11:"TurkTelecom";s:3:"org";s:0:"";s:2:"as";s:18:"AS47331 TTNet A.S.";s:5:"query";s:13:"85.107.65.120";}
1

2 Answers 2

1

It is serialized PHP data. You can use unserialize to convert it back to legitimate array.

See also:


Code example

<?php

function curl_get_contents($url) {
    // Initiate the curl session
    $ch = curl_init();
    // Set the URL
    curl_setopt($ch, CURLOPT_URL, $url);
    // Removes the headers from the output
    curl_setopt($ch, CURLOPT_HEADER, 0);
    // Return the output instead of displaying it directly
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // Execute the curl session
    $output = curl_exec($ch);
    // Close the curl session
    curl_close($ch);
    // Return the output as a variable
    return $output;
}

$ip = "151.101.193.69";
$output = unserialize(curl_get_contents("http://ip-api.com/php/".$ip));

print_r($output);

Output

Array
(
    [status] => success
    [country] => Canada
    [countryCode] => CA
    [region] => QC
    [regionName] => Quebec
    [city] => Montreal
    [zip] => H4X
    [lat] => 45.5017
    [lon] => -73.5673
    [timezone] => America/Toronto
    [isp] => Fastly
    [org] => Fastly
    [as] => AS54113 Fastly
    [query] => 151.101.193.69
)
Sign up to request clarification or add additional context in comments.

Comments

1

Its a json variable, you need use json_decode function for transform json to array

$result = json_decode($output, true);

1 Comment

It's not a JSON, it is serialized PHP data. See php.net/manual/en/function.serialize.php

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.