我正在尝试使用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解码返回空结果。我认为唯一的方法是打破该字符串?感谢您提前提示。我想从结果中获取国家/地区名称。
答案 0 :(得分:4)
根据API文档,您还可以使用get_json.php
刚刚使用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);
答案 1 :(得分:3)
使用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;
答案 2 :(得分:0)
如果您不介意,请使用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;