如何将 PHP cURL 数据转换为数组?

How can I convert PHP cURL data to array?

我正在使用 api 通过 IP 地址检测用户的位置。为此,我不想使用 file_get_contents,而是想使用我在下面编写的 cURL 函数。但是我得到的字符串非常复杂。如何将此字符串转换为清晰的数组?

我的代码

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;

结果

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";}

它是序列化的PHP数据。您可以使用 unserialize 将其转换回合法数组。

另请参阅:


代码示例

<?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);

输出

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
)

它是一个json变量,你需要使用json_decode函数将json转换成数组

$result = json_decode($output, true);