开发者

How to get country name from IP address in php [duplicate]

开发者 https://www.devze.com 2023-01-25 01:45 出处:网络
This question already has answers here: How do you parse and process HTML/XML in PHP? (31 answers) Closed 9 years ago.
This question already has answers here: How do you parse and process HTML/XML in PHP? (31 answers) Closed 9 years ago.

I want to find country, city, latitude and longitude from IP address using php. I am using this url and it is returning data in xml format.

http://www.ipgp.net/api/xml/122.163.6.58

The data is开发者_运维知识库 coming like this:

<IpLookup>
    <Ip>122.163.6.58</Ip>
    <Code>IN</Code>
    <Country>India</Country>
    <Flag>http://www.ipgp.net/flags/in.png</Flag>
    <City>Calcutta</City>
    <Region>West Bengal</Region>
    <Isp></Isp>
    <Lat>22.5697</Lat>
    <Lng>88.3697</Lng>
</IpLookup>

Can anybody suggest how to parse and get the result


Use the XML parser included in PHP?


Use simplexml_load_string().


I've been using this personally: http://ipinfodb.com/

The examples are very clear and concise and the API is very fast.

Good luck.


The use of API in PHP has already described in their website. Why you use but don't read?

http://www.ipgp.net/developer-tools/


I'll suggest you to use xpath this is more easier schema for accessing the attributes. for example for your current data i have the following:

$file = 'file.xml';
$xml = new SimpleXMLElement($file, NULL, TRUE);
$ipz = $xml->xpath("/IpLookup/Ip");
$country = $xml->xpath("/IpLookup/Country/");
foreach($ipz as $ip)
{
    foreach($country as $country)
    {
      echo $ip.'<br/>';
      echo $country.'<br/>';
    }
}

this code will return you the ip and the country for your current xml. you can edit it in your own way.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号