我创建了一个API
这是URL
http://geoip.mediaciptainformasi.co.id/ip.php?ip=1.1.1.1
并且输出像{<1}}一样响应
json
如何获取特定键值,例如其他网站的{
"ip_address": "1.1.1.1",
"Jumlah Akses per hari": "1 kali",
"ip_from": "16843008",
"ip_to": "16843263",
"country_code": "AU",
"country_name": "Australia",
"region_name": "Queensland",
"city_name": "Brisbane",
"latitude": "-27.46794",
"longitude": "153.02809",
"zip_code": "4000",
"time_zone": "+10:00"
}
和country_name
?
我已在city_name
上尝试了此操作,但无法正常工作
localhost
答案 0 :(得分:0)
使用cURL:
<?php
// when you want to display errors by overriding `php.ini`
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// function to return cURL response
function get_data_function($ip)
{
if ($ip == NULL){
$ip = "1.1.1.1";
}
// base url
$url = "http://geoip.mediaciptainformasi.co.id/ip.php/?ip=".$ip;
$ch = curl_init($url);
// cURL OPTIONS:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
// Check for errors and display the error message
if($errno = curl_errno($ch)) {
$error_message = curl_strerror($errno);
echo "cURL error ({$errno}):\n {$error_message}";
}
if (isset($result)) {
$response = json_decode($result, true);
}
curl_close($ch);
return $response;
}
// calling method with desired IP string
$response = get_data_function("110.138.84.204");
// get specific value by its json key
echo "Country Name " . $response['country_name'];
echo "</br>";
echo "City Name " . $response['city_name'];
echo "</br>";
echo "</br>";
// in case of view full response
var_dump($response);
?>
在localhost
答案 1 :(得分:-2)
$url = "http://geoip.mediaciptainformasi.co.id/ip.php/?ip=110.138.84.204";
$jsondata = file_get_contents($url);
$obj = json_decode($jsondata);
// Use this to see object, after that you can do what you want to $obj
print_r($obj);