我如何使用正则表达式获取有关 IP 到位置 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;
当我执行 echo $regex 时,我总是失败,我该如何解决这个问题
最佳答案
正如 Aaron 所建议的那样。最好不要重新发明轮子,所以尝试用 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
关于用于 IP 到位置 API 的 PHP 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3126055/