我如何使用Regex获取有关IP到Location API的信息
这是API
http://ipinfodb.com/ip_query.php?ip=74.125.45.100
我需要获得国家名称,地区/州和城市.
我试过这个:
$ip = $_SERVER["REMOTE_ADDR"];
$contents = @file_get_contents('http://ipinfodb.com/ip_query.PHP?ip=' . $ip . '');
$pattern = "/<CountryName>(.*)<CountryName>/";
preg_match($pattern, $contents, $regex);
$regex = !empty($regex[1]) ? $regex[1] : "FAIL";
echo $regex;
解决方法:
正如亚伦建议的那样.最好不要重新发明轮子,所以尝试使用simplexml_load_string()解析它
// Init the CURL
$curl = curl_init();
// Setup the curl settings
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 0);
// grab the XML file
$raw_xml = curl_exec($curl);
curl_close($curl);
// Setup the xml object
$xml = simplexml_load_string( $raw_xml );
您现在可以访问$xml变量的任何部分作为对象,这里有关于您发布的内容的示例.
<Response>
<Ip>74.125.45.100</Ip>
<Status>OK</Status>
<CountryCode>US</CountryCode>
<CountryName>United States</CountryName>
<RegionCode>06</RegionCode>
<RegionName>California</RegionName>
<City>Mountain View</City>
<ZipPostalCode>94043</ZipPostalCode>
<Latitude>37.4192</Latitude>
<Longitude>-122.057</Longitude>
<Timezone>0</Timezone>
<Gmtoffset>0</Gmtoffset>
<Dstoffset>0</Dstoffset>
</Response>
现在,在将此XML字符串加载到simplexml_load_string()之后,您可以像这样访问响应的IP地址.
$xml->IP;
simplexml_load_string()会将格式良好的XML文件转换为可以操作的对象.我唯一能说的就是去尝试一下然后玩吧
编辑:
资源
http://www.php.net/manual/en/function.simplexml-load-string.php
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。