用于IP到位置API的PHP Regex

xZe*_*rox 5 php regex xml api geoip

我如何使用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;
Run Code Online (Sandbox Code Playgroud)

当我回复$ regex时,我总是得到失败怎么能解决这个问题

War*_*les 3

正如亚伦所建议的那样。最好不要重新发明轮子,所以尝试用 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 );
Run Code Online (Sandbox Code Playgroud)

您现在可以将 $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> 
Run Code Online (Sandbox Code Playgroud)

现在,将此 XML 字符串加载到 simplexml_load_string() 中后,您可以像这样访问响应的 IP 地址。

$xml->IP;
Run Code Online (Sandbox Code Playgroud)

simplexml_load_string() 会将格式良好的 XML 文件转换为您可以操作的对象。我唯一能说的就是去尝试并使用它

编辑:

来源 http://www.php.net/manual/en/function.simplexml-load-string.php