2010-01-21 76 views
1

我使用下面的PHP:PHP使用simplexml_load_file趕上403

$xml = simplexml_load_file($request_url) or die("url not loading"); 

我用:

$status = $xml->Response->Status->code; 

要檢查響應的狀態。 200一切都好,繼續。

但是,如果我得到一個403訪問被拒絕的錯誤,我該如何在PHP中捕獲這個,這樣我可以返回一個用戶友好的警告?

回答

8

要檢索來自simplexml_load_file()的調用的HTTP響應代碼,我知道的唯一方法是使用PHP的鮮爲人知的$http_response_header。這個變量被自動創建爲一個包含每個響應頭的數組,每次你通過HTTP包裝器發出一個HTTP請求。換句話說,每次你使用simplexml_load_file()file_get_contents()與開始的URL的「http://」

您可以查看其內容與諸如

print_r()
$xml = @simplexml_load_file($request_url); 
print_r($http_response_header); 

在你的情況,不過,你可能想要單獨檢索XML,然後測試您是否得到4xx響應,如果不是,請將正文傳遞給simplexml_load_string()。例如:

$response = @file_get_contents($request_url); 
if (preg_match('#^HTTP/... 4..#', $http_response_header[0])) 
{ 
    // received a 4xx response 
} 

$xml = simplexml_load_string($response); 
+0

我應該更清楚一點 - 雖然這有效,並允許我捕捉錯誤並停止腳本嘗試做更多的事情。我仍然收到默認警告消息: 警告:file_get_contents(http://domain.com)[function.file-get-contents]:無法打開流:HTTP請求失敗! HTTP/1.0 403 Forbidden 捕捉它們的原因是我提出了幾個請求,並希望在發生錯誤時乾淨地捕捉錯誤,並提供用戶友好的警告而不是默認值。 – Scoobler 2010-01-25 01:06:38

+1

然後您使用靜音操作符@如更新後的代碼片段中所示。 http://docs.php.net/manual/en/language.operators.errorcontrol.php – 2010-01-25 01:49:52