【问题标题】:Get country from curl request using php使用 php 从 curl 请求中获取国家/地区
【发布时间】:2015-05-26 06:07:11
【问题描述】:

我正在开发我尝试使用 curl 的应用程序。在此之前我尝试使用 file_get_contents() 但由于 allow_url 问题而无法在我的服务器上运行(我尝试联系托管但尚未解决所以我尝试替代)。所以我使用 curl 从远程站点获取数据。我使用此代码获取数据:

$url="http://api.hostip.info/get_html.php?ip=182.188.193.238";
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

print_r($result);

当我打印时,我得到Country: PAKISTAN (PK) City: Lahore IP: 182.188.193.238。我想从这个字符串中得到国家。我试过这样但得到像$data = json_decode($result,true); 这样的空结果。 Json 解码返回空结果。我认为唯一的方法是破坏该字符串?感谢您提前提供任何提示。我想从结果中获取国家/地区名称。

【问题讨论】:

  • 那不是 JSON。因此,您必须使用带有正则表达式的preg_match() 才能从响应中获取它。

标签: php html curl


【解决方案1】:

根据 API 文档,您还可以使用 get_json.php 获得 json 响应

只是使用get_json.php 而不是get_html.php

你的代码应该是:

$url="http://api.hostip.info/get_json.php?ip=182.188.193.238";
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
$data = json_decode($result,true);
print_r($data);

【讨论】:

  • 不错的一个。我认为这是最干净的解决方案:-)。
【解决方案2】:

使用preg_match

preg_match('/Country: (?P<country>\w+)/', $result, $matches);
print_r($matches);

输出:

Array
(
    [0] => Country: PAKISTAN 
    [country] => PAKISTAN
    [1] => PAKISTAN
)

所以你会得到国家名称

$countryName = $matches['country'];

正如@hardik solanki 所说,还有JSON 端点get_json.php

$url = "http://api.hostip.info/get_json.php?ip=182.188.193.238";

要从 JSON 响应中获取国家/地区,请使用:

$response = json_decode($result);
$countryName = $response->country_name;

【讨论】:

  • 如果 OP 只想要这个国家,我认为这是最快的方式。
【解决方案3】:

如果您不介意,请使用 get_content

$content = get_content("http://api.hostip.info/get_html.php?ip=182.188.193.238");

$country = stristr($content, 'Country: ');

$country = stristr($country, 'City:', true);

$country= ucfirst(str_replace('Country: ', '', $country));

echo $country;

【讨论】:

    猜你喜欢
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    相关资源
    最近更新 更多