【问题标题】:Parsing an external HTML page with PHP使用 PHP 解析外部 HTML 页面
【发布时间】:2011-09-12 17:14:02
【问题描述】:

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

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

然后页面会写“US”...

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

谢谢。

【问题讨论】:

  • 您要检查什么?如果是美国?
  • 是的,如果是美国则返回 true,否则返回 false。

标签: php html-parsing


【解决方案1】:

您可以使用以下内容。将$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';
}

【讨论】:

  • 函数名有错别字,你能改正吗?
  • 谢谢,这部分工作,但它返回给我 XX 对于我测试的每个 IP,可能是应该使用该函数的一些语言参数还是什么?
  • @Sean87 不,IP 只是在他们的数据库中不存在。
  • @Sean87 添加了检查 IP 是否存在于其数据库中的功能。
【解决方案2】:

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';
}

【讨论】:

  • 为什么这是个问题? curl 通常比file_get_contents 执行得更快,并且允许您设置更详细的设置。没有理由说它不是 file_get_contents 的可行替代方案。
  • 谢谢,这会在 outpot 的末尾添加一个 1。例如 US1 我也认为它比 file_get_contents 慢一点??
  • @atno curl 比 file_get_contents 更快、更灵活
  • @Sean87 那是我的错,忘记添加CURLOPT_RETURNTRANSFER。没有它,curl_exec 返回 1 并输出页面。更新后的代码可以正常工作。
【解决方案3】:

由于该页面除了国家代码外不输出任何内容,因此不需要解析。对返回的 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;
}

【讨论】:

  • 不是内容!是内容!并且file_get_contents() 函数的输出可以用trim() 函数修剪。
猜你喜欢
  • 2011-07-30
  • 1970-01-01
  • 1970-01-01
  • 2014-01-08
  • 2010-12-03
  • 1970-01-01
  • 1970-01-01
  • 2014-08-31
  • 1970-01-01
相关资源
最近更新 更多