使用PHP解析外部HTML页面


Parsing an external HTML page with PHP

我正在尝试使用IP的国家/地区检测,这是来自http://www.hostip.info/use.html

因此,如果你在浏览器中放入以下内容:http://api.hostip.info/country.php?ip=12.24.25.26

然后页面会写"美国"。。。

现在我的问题是如何在php代码中的IFELSE lopp中使用它?我想我必须解析那个HTML页面,但目前我还不知道,会有一些帮助!

谢谢。

由于该页面不输出除国家代码以外的任何内容,因此不需要进行解析。对返回的HTML进行简单的检查就可以了

<?php
$ip = '12.24.25.26';
$country = file_get_contents('http://api.hostip.info/country.php?ip='.$my_ip); // Get the actual HTML
if($country === "US") {
    echo "It is US";
} else {
    echo "It is not US. It is " . $country;
}

CURL应该做你需要它做的事情。

$url = "http://api.hostip.info/country.php?ip=[put_your_ip_here]";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($curl);
curl_close($curl);
if(preg_match('/^us$/i', $output)) {
  echo 'Is US';
} else {
  echo 'Something else';
}

您可以使用以下内容。将$my_ip更改为您喜欢的IP。

<?php
$my_ip = '12.24.25.26';
$my_country = file_get_contents('http://api.hostip.info/country.php?ip='.$my_ip);
if(strstr($my_country,'US'))
{
    echo $my_country . ' found.';
}
elseif(strstr($my_country,'XX'))
{
    echo 'IP: ' . $my_ip . 'doesn''t exists in database';
}