簡體   English   中英

從GET URL中提取json響應中特定鍵的值

[英]extract value of specific key in json response from GET URL

我創建了一個API

這是URL http://geoip.mediaciptainformasi.co.id/ip.php?ip=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_namecity_name

我已經在localhost上嘗試過了,但是不起作用

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

?>

使用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上工作正常

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM