file_get_contents()处理错误消息

时间:2015-08-02 15:09:15

标签: php

我有一个工作功能来获得外部网站的速度。

$t = microtime( TRUE );
file_get_contents( "http://www.example.org" );
$t = microtime( TRUE ) - $t;
print "It took $t seconds!";

但是,如果外部网址已关闭,则会打印此内容;

Warning: file_get_contents(http://www.example.org): failed to open stream: HTTP request failed! 
HTTP/1.0 500 Internal Server Error in /home/china/public_html/dene.php on line 47
It took 14.4556088448 seconds!

打印“Site down”而不是出现错误的核心方法是什么?

1 个答案:

答案 0 :(得分:2)

您需要检查对file_get_contents的调用是否成功:

$t = microtime( TRUE );
@$content = file_get_contents( "http://www.example.org" );
if($content == FALSE) {
    print "Site down"; // or other problem
} else {
    $t = microtime( TRUE ) - $t;
    print "It took $t seconds!";
}

@可以取消警告。