2012-04-29 85 views
2

考慮以下幾點:如何在get_headers()嘗試解析無法解析的主機時捕獲錯誤?

$url = 'http://psyng.com/u/9716602b'; 
$headers = get_headers($url, 1); 
print_r($headers); 

由於域psyng.com是無法解決的,這段代碼的結果:

Warning: get_headers(): php_network_getaddresses: getaddrinfo failed: 
No such host is known 

然後腳本停止運行。有沒有辦法讓腳本的其餘部分繼續運行 - 換句話說:抓住錯誤,並繼續解決下一個URL?所以像這樣:

$url = 'http://psyng.com/u/9716602b'; 
$headers = get_headers($url, 1); 
if ($headers == 'No such host is known') { 
    // nevermind, just move on to the next URL in the list... 
} 
else { 
    // resolve header stuff... 
} 
+0

get_headers不一致性:http://stackoverflow.com/questions/12781795/get-headers-inconciptency – Baba 2012-10-08 15:39:56

回答

3

腳本不應停止運行,因爲生成的消息只是一個警告。我自己測試了這個腳本,這就是我看到的行爲。您可以在the documentation看到get_headers()會在失敗時返回FALSE所以你的情況實際上應該是

if ($headers === FALSE) { 
    // nevermind, just move on to the next URL in the list... 
0

功能get_headers返回一個布爾結果; print_r的目的是以可讀格式返回布爾值。

<?php 
$url = 'http://psyng.com/u/9716602b'; 
$headers = get_headers($url, 1); 
if ($headers === FALSE) { //Test for a boolean result. 
    // nevermind, just move on to the next URL in the list... 
} 
else { 
    // resolve header stuff... 
} 
?>