簡體   English   中英

使用php從curl請求獲取國家

[英]Get country from curl request using php

我正在嘗試使用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 。我想從這個Country: PAKISTAN (PK) City: Lahore IP: 182.188.193.238中獲取國家。我嘗試這樣,但是得到空的結果,例如$data = json_decode($result,true); JSON解碼返回空結果。我認為唯一的方法是打破那個字符串? 感謝您提前提供任何提示。我想從結果中獲取國家/地區名稱。

根據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);

使用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;

如果您不介意,請使用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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM