我正在使用file_get_contents()访问URL。
file_get_contents('http://somenotrealurl.com/notrealpage');
如果URL不是真实的,它将返回此错误消息。我如何才能使其优雅地出错,以便使我知道该页面不存在并采取相应措施而不显示此错误消息?
file_get_contents('http://somenotrealurl.com/notrealpage') [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found in myphppage.php on line 3
例如在zend中,您可以说: if ($request->isSuccessful())
if ($request->isSuccessful())
$client = New Zend_Http_Client(); $client->setUri('http://someurl.com/somepage'); $request = $client->request(); if ($request->isSuccessful()) { //do stuff with the result }
您需要检查HTTP响应代码:
function get_http_response_code($url) { $headers = get_headers($url); return substr($headers[0], 9, 3); } if(get_http_response_code('http://somenotrealurl.com/notrealpage') != "200"){ echo "error"; }else{ file_get_contents('http://somenotrealurl.com/notrealpage'); }