简体   繁体   中英

extract value of specific key in json response from GET URL

i created an API

this is URL http://geoip.mediaciptainformasi.co.id/ip.php?ip=1.1.1.1 and the output is in json response like this

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

how can i get the specific key value, like country_name and city_name for other website?

I've tried this on localhost but doesn't work

<?php

    $url = "http://geoip.mediaciptainformasi.co.id/ip.php/?ip=110.138.84.204";
    $jsondata = file_get_contents($url);
    $obj = json_decode($jsondata);
    echo $obj->latitude;
    echo $obj->country_name;

?>

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

Works fine on localhost

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM