循环不使用完整的 IP,而只使用第一个数字


Loop is not using the full IP but only the first number

我现在正在尝试获取数据库中每个 ip 的位置,问题是它只使用第一个数字而不是由于某种原因使用完整的 ip,所以我收到错误:

警告:file_get_contents(ipinfo.io/8):无法打开流:HTTP 请求失败!HTTP/1.1 404 未在 中找到

现在是我的问题,因为我不再有线索,如何使其与完整的 ip 一起工作。

$result_ip = $dbhandle->query("SELECT ip FROM email");
$row_cnt_ip = $result_ip->num_rows;
$ip_rows = $result_ip->fetch_array(MYSQLI_ASSOC);
$country_ip_data = array();
foreach ($ip_rows as $ip_row) {
    $ip = $ip_row['ip'];
    if (!$ip) {
        continue;
    }
    $details = json_decode(file_get_contents("http://ipinfo.io/{$ip}"));
    $country = $details->country;
    if (!isset($country_ip_data[$country])) {
        $country_ip_data[$country] = array();
    }
    $country_ip_data[$country][] = $ip;
}
var_dump($country_ip_data);

最终结果应该是一个包含所有国家/地区的数组,因此我可以在每个国家/地区对其进行过滤并将它们放在地图图表中。

问题出在行$ip_rows = $result_ip->fetch_array(MYSQLI_ASSOC); .mysqli fetch_array 方法从查询的数据中返回一行,因此您需要遍历所有行:

$result_ip = $dbhandle->query("SELECT ip FROM email");
$row_cnt_ip = $result_ip->num_rows;
$country_ip_data = array();
// use a while loop to extract one row's data at a time
while ($ip_row = $result_ip->fetch_array(MYSQLI_ASSOC)) {
    $ip = $ip_row['ip'];
    if (!$ip) {
        continue;
    }
    $details = json_decode(file_get_contents("http://ipinfo.io/{$ip}"));
    $country = $details->country;
    if (!isset($country_ip_data[$country])) {
        $country_ip_data[$country] = array();
    }
    $country_ip_data[$country][] = $ip;
}
var_dump($country_ip_data);
请尝试

以下操作:

$result_ip = $dbhandle->query("SELECT ip FROM email");
$row_cnt_ip = $result_ip->num_rows;
$country_ip_data = array();
while ($ip_row = $result_ip->fetch_array(MYSQLI_ASSOC)) {
    $ip = $ip_row['ip'];
    if (!$ip) {
        continue;
    }
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, "http://ipinfo.io/{$ip}"); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    $output = curl_exec($ch); 
    $details = json_decode($output);
    curl_close($ch); 
    $country = $details->country;
    if (!isset($country_ip_data[$country])) {
        $country_ip_data[$country] = array();
    }
    $country_ip_data[$country][] = $ip;
}
var_dump($country_ip_data);