2011-06-10 68 views
1

我想通過IP,從http://www.hostip.info/use.html解析外部HTML頁面用PHP

所以,如果你把你的瀏覽器類似的API使用國家檢測: http://api.hostip.info/country.php?ip=12.24.25.26

後,頁面會寫「美國」...

現在我的問題是我怎樣才能在我的php代碼中使用IF ELSE lopp?我想我必須解析HTML頁面,但目前我不知道,一些幫助將appriciated!

謝謝。

+0

你想檢查什麼?如果是美國? – alexn 2011-06-10 18:15:45

+0

是的,如果是美國則返回true,否則返回false。 – 2011-06-10 18:18:49

回答

4

由於該頁面不高於全國其他代碼輸出任何東西,也沒有需要解析。對返回的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; 
} 
+0

這不是爭辯!這是內容!而'file_get_contents()'函數的輸出可以用'trim()'函數修剪。 – kongr45gpen 2011-06-10 18:22:33

3

您可以使用以下內容。將$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'; 
} 
+0

功能名稱中的錯字,你能修復嗎? – MitMaro 2011-06-10 18:23:56

+0

@mitmaro完成隊友 – afarazit 2011-06-10 18:28:56

+0

謝謝,這部分工作,但它返回給我每個IP我XX測試,可能是某種語言的參數,應該使用該功能或​​什麼? – 2011-06-10 18:29:15

4

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

方式太多行 – afarazit 2011-06-10 18:29:17

+1

爲什麼這是一個問題? 'curl'通常比'file_get_contents'執行得更快,並允許你設置更多的詳細設置。沒有理由爲什麼它不是'file_get_contents'的可行替代方案。 – scurker 2011-06-10 18:33:37

+0

謝謝,這增加了一個1在結束的時候。例如US1另外我認爲它比file_get_contents慢一點? – 2011-06-10 18:35:30