当我将这个url http://www.ilpost.it/2014/02/25/peanuts-2014-febbraio-25/ (页面是空的,但在某种意义上仍然存在)与file_get_contents一起使用时,它会给我以下警告:
Warning: file_get_contents(http://www.ilpost.it/2014/02/16/peanuts-2014-febbraio-16/) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found in [...my php url...]
即使我将函数放在这样的条件下
if (file_get_contents($url_to_feed) === FALSE){..}我得到警告,然后得到条件的结果。
如何解决此问题并避免出现警告?
发布于 2014-02-16 23:58:14
通过使用file_get_contents,您是在做一个假设。您假定该文件存在。
在本地文件系统上,您通常会首先使用file_exists进行检查,但这最终会导致每次都向另一个服务器发出两个请求……所以可能不是个好主意。
就我个人而言,我会使用套接字。
$fp = fsockopen("www.ilpost.it",80);
if( $fp) { // connection established
fputs($fp,"GET /2014/02/25/peanuts-2015-febbraio-25/ HTTP/1.0\r\n"
."Host: www.ilpost.it\r\n"
."\r\n");
$return = "";
$headers = "firstline";
while(!feof($fp)) {
if( $headers) {
$line = trim(fgets($fp));
if( $headers == "firstline") {
list(,$status,$text) = explode(" ",$line,3);
if( $status != "200") { /* do something... or not! */ }
$headers = "remaining";
}
if( !$line) $headers = false;
}
else $return .= fgets($fp);
}
fclose($fp);
}当然,这需要大量的代码,但这就是定义您自己的函数的目的;)
https://stackoverflow.com/questions/21813484
复制相似问题