Pregunta

<?

$ip = '95.79.1.36'; //russian ip for test
$str = 'http://ipgeobase.ru:7020/geo?ip='.$ip;
$content = file_get_contents($str);
preg_match_all('#<country>(.*)(</country>)#Usi', $content, $matches); 
$country = $matches[0][0];
preg_match_all('#<city>(.*)(</city>)#Usi', $content, $matches); 
$city = $matches[0][0];
if($country == 'RU'){
echo 'City: '.$city.'';
}else{
echo 'Country: '.$country.'';
}

?>

The problem is $country == 'RU' , not work, my question is why ?

Thanks )))

¿Fue útil?

Solución

You probably shouldn't be parsing HTML/XHTML/XML with Regex. See: RegEx match open tags except XHTML self-contained tags

I recommend using PHP's SimpleXML parser. The following worked for me:

<?php
$ip = '95.79.1.36'; //russian ip for test
$str = 'http://ipgeobase.ru:7020/geo?ip='.$ip;

$results = simplexml_load_file($str);
$country = $results->ip->country;
$city = $results->ip->city;

if($country == 'RU'){
echo 'City: '.$city.'';
}else{
echo 'Country: '.$country.'';
}

?>

Otros consejos

Your server probably does not allow_url_fopen (php.ini directive). Anyway, the technology you are looking for for this particular case is cURL : https://php.net/curl.

I'd be delighted to provide more explanations about your code specifically, and even provide cURL code samples, once you'll have edited your question properly, with more information and attempts resulting of your efforts.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top