There is a json line of the following form:

{["name_ru"]=> string(8) "Киев"} 

I am trying to parse in the following ways, and either NULL or an empty string is displayed:

 $geo = !$is_bot ? json_decode(file_get_contents('http://api.sypexgeo.net/json/'.$_SERVER['HTTP_X_FORWARDED_FOR']), true) : []; echo $geo->name_ru; // выводит пустую строку print_r($geo->{"name_ru"}); //выводит пустую строку var_dump($geo->{'name_ru'}); //выводит NULL //var_dump($geo); // выводит массив с валидными данными 

How do I get the right value?

  • 1) this is not JSON: {["name_ru"]=> string(8) "Киев"} 2) SxGeo returns completely different data 3) check the return file_get_contents() (maybe you exceeded the limits or something else wrong) 4) show IP for which there is a request - PinkTux

1 answer 1

Strange you have some kind of JSON specified at the beginning. And this is also not clear:

 echo $geo->name_ru 

SxGeo returns the following structure, after json_decode() :

 Array ( [ip] => 111.222.333.444 [city] => Array ( [id] => 498817 [lat] => 59.93863 [lon] => 30.31413 [name_ru] => Санкт-Петербург [name_en] => Saint Petersburg [name_de] => Sankt Petersburg [name_fr] => Saint-Pétersbourg [name_it] => San Pietroburgo [name_es] => San Petersburgo [name_pt] => São Petersburgo [okato] => 40 [vk] => 2 [population] => 5191690 ) [region] => Array ( [id] => 536203 [lat] => 59.92 [lon] => 30.25 [name_ru] => Санкт-Петербург [name_en] => Sankt-Peterburg [name_de] => Sankt Petersburg [name_fr] => Saint-Pétersbourg [name_it] => San Pietroburgo [name_es] => San Petersburgo [name_pt] => São Petersburgo [iso] => RU-SPE [timezone] => Europe/Moscow [okato] => 40 [auto] => 78, 98, 178 [vk] => 0 [utc] => 3 ) [country] => Array ( [id] => 185 [iso] => RU [continent] => EU [lat] => 60 [lon] => 100 [name_ru] => Россия [name_en] => Russia [name_de] => Russland [name_fr] => Russie [name_it] => Russia [name_es] => Rusia [name_pt] => Rússia [timezone] => Europe/Moscow [area] => 17100000 [population] => 140702000 [capital_id] => 524901 [capital_ru] => Москва [capital_en] => Moscow [cur_code] => RUB [phone] => 7 [neighbours] => GE,CN,BY,UA,KZ,LV,PL,EE,LT,FI,MN,NO,AZ,KP [vk] => 1 [utc] => 3 ) [error] => [request] => -8 [created] => 2016.10.08 [timestamp] => 1475955522 ) 

Therefore, the Russian name of the city is mined as follows:

 // без IP будет обрабатываться IP машины/прокси, откуда идёт запрос $data = file_get_contents( 'http://api.sypexgeo.net/json/' ); if( $data ) { $geo = json_decode( $data, true ); print $geo['city']['name_ru']; // <<< вот так! }