用于 IP 到位置 API 的 PHP 正则表达式

标签 php xml regex api geoip

我如何使用正则表达式获取有关 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/

相关文章:

php - INSERT 不适用于 PDO 准备好的语句

php - MySQL - 一组用户的最新行

java - 在 java 中访问 xml 元素中的属性

regex - 如何查找和替换字符串列中数字之间的空格?

c# - 如何从字符串中提取前 3 个独立字符?

javascript - RegEx - 查找模式之间的字符串

php - 将 SQL 结果分类并在表格 PhP 中显示

php - 是否可以向 Laravel 模型添加非持久属性?

xml - DocBook-XML 和网络帮助

xml - 为什么 XML namespace 是 HTTP 地址?