【问题标题】:How can I convert PHP cURL data to array?如何将 PHP cURL 数据转换为数组?
【发布时间】:2021-06-30 22:32:18
【问题描述】:

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

我的代码

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 arrays curl file-get-contents


【解决方案1】:

是序列化的 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
)

【讨论】:

    【解决方案2】:

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

    $result = json_decode($output, true);
    

    【讨论】:

    猜你喜欢
    • 2021-03-09
    • 2019-09-01
    • 2017-03-30
    • 2016-08-29
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    • 2017-08-09
    相关资源
    最近更新 更多