我如何使用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