使用PHP从db-ip.com进行JSON解码api

时间:2019-03-04 18:00:30

标签: php json api curl file-get-contents

我对db-ip.com api有一些问题,该api显示有关访问者ip的信息。我的脚本仅打印

标签,而在两者之间不打印任何内容。我需要对api中的所有参数进行解码和打印,例如来自以下链接:http://db-ip.com/178.133.109.106。
请帮助我。

<?php

// get ip
if (!empty($_SERVER["HTTP_CLIENT_IP"])){

    $ip = $_SERVER["HTTP_CLIENT_IP"];

}

elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){

    $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];

}

else {

    $ip = $_SERVER["REMOTE_ADDR"];

}



$json_url = "http://api.db-ip.com/v2/free/$ip";
$json = file_get_contents($json_url);
$json=str_replace('}, ]',"} ]",$json);
$data = json_decode($json);

echo "<pre>";
print_r($data);
echo "</pre>";
?>

1 个答案:

答案 0 :(得分:1)

尝试此代码

<?php
    header('Content-Type: application/json');
    // get ip
    $ip = $_SERVER['HTTP_CLIENT_IP'] ? $_SERVER['HTTP_CLIENT_IP'] : ($_SERVER['HTTP_X_FORWARDED_FOR'] ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']); //$ip = '178.133.109.106';

    $json_url = "http://api.db-ip.com/v2/free/$ip";
    $data = file_get_contents($json_url);
    print_r($data);

?>

查看此链接
http://tpcg.io/Gv3KLv