-3

I use some website that give me information about IP but the information that that website return in JSON and I don't know the JSON. I want to use this to check the user if it is from IR do something but I dont know how to use JSON in php,
Here is the JSON that the website return:

{"address":"0.0.0.0.0","country":"IR","stateprov":"somewhere ","city":"Tehr\somewhere (somewhere)"}

I want to save the country in a variable and add this code to my website:

<?php
if($country == 'IR'){
//Do somethong  
}

$country is the country name that return from the website,

Adrian Thompson Phillips
  • 6,893
  • 6
  • 38
  • 69
King_Far
  • 3
  • 2

4 Answers4

4

You'll need to use json_decode().

$s = '{"address":"0.0.0.0.0","country":"IR","stateprov":"somewhere ","city":"Tehrsomewhere (somewhere)"}';

$d = json_decode($s);

Which returns:

stdClass Object
(
    [address] => 0.0.0.0.0
    [country] => IR
    [stateprov] => somewhere 
    [city] => Tehrsomewhere (somewhere)
)

That would allow you to check the country/other fields like this:

if($d->country == 'IR') {
    // do something
}

NOTE: you had an error (invalid json) in your "city" field, the \ makes it invalid.

Example


You can ensure that your json is valid by checking it at JSON Lint.

Darren
  • 13,050
  • 4
  • 41
  • 79
0

I think you are looking for the function json_decode.It decodes the JSON string

See the documentation here

Avinash Babu
  • 6,171
  • 3
  • 21
  • 26
0

First of all i would like to inform you that given json is not valid. "city" : "Tehr\somewhere (somewhere)" is not valid because of "\".

So change it into below given format.

$jsonEncode = { "address": "0.0.0.0.0","country": "IR","stateprov": "somewhere ","city": "There somewhere (somewhere)"}

$jsonDecode = json_decode($jsonEncode,true);

Now you will get the value in array format.

Array(
    [address] => 0.0.0.0.0
    [country] => IR
    [stateprov] => somewhere 
    [city] => There somewhere (somewhere)

);

print_r($jsonDecode['city']); will give you city name or details

Kevin
  • 41,694
  • 12
  • 53
  • 70
Anjali
  • 43
  • 5
0

You have to first decode this json string.

$data = '{"address":"0.0.0.0.0","country":"IR","stateprov":"somewhere ","city":"Tehr\somewhere (somewhere)"}';

$decodeData = json_decode($data);

Then use this decode json string in php like this.

if($decodeData->country == 'IR'){
//Do somethong  
}