Access JSON values with PHP

Asked

Viewed 44 times

-2

I have the following API: https://proxycheck.io/v2/42.131.121.100?vpn=1&asn=1

{
"status": "ok",
"42.131.121.100": {
    "continent": "Asia",
    "country": "China",
    "isocode": "CN",
    "latitude": 34.7732,
    "longitude": 113.722,
    "proxy": "no",
    "type": "Business"
    }
}

How do I access only what is in "country" and "type" and put in a variable?

  • will always be like this? this layout changes at some point, or this search api changes the parameters?

  • always so, the layout will always be the same

  • as the same values, for example 42.131.121.100 will always be that number?

  • This value will change according to what is passed in the API link, but for example we can take into account a fixed value in this IP always.

  • You have to write a code that fits in several aspects. complicated until you answer

  • I don’t know if it helps, but in Python it would look like this: https://answall.com/questions/486831/acessar-values-de-um-json-em-python I need to do the same thing, only in PHP

Show 1 more comment

1 answer

2


Basically, after retrieving this information with Curl of transform into with json_decode and then pass the keys in sequence as described in layout of , code example:

<?php
    $url = 'https://proxycheck.io/v2/42.131.121.100?vpn=1&asn=1';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $json = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($httpCode === 200) {
        $array = json_decode($json, TRUE);
        $country = $array['42.131.121.100']['country'];
        $type = $array['42.131.121.100']['type'];
    }
    curl_close($ch);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.