如何处理 PHP 中 file_get_contents() 函数的警告?

369

我写了一个像这样的 PHP 代码

$site="http://www.google.com";
$content = file_get_content($site);
echo $content;

但是当我从$site中删除"http://"时,我会收到以下警告:

警告:file_get_contents(www.google.com)[function.file-get-contents]:无法打开流:

我尝试了trycatch,但没有起作用。


2
还有一种有趣的方法: https://dev59.com/O2w15IYBdhLWcg3wSJo3 - Hugo Stieglitz
相关链接:https://dev59.com/7nI-5IYBdhLWcg3wI0p9 - Fr0zenFyr
在此处使用try-catch与set_error_handler函数,如此所述:https://dev59.com/mXVC5IYBdhLWcg3whBWj#3406181 - MingalevME
3
如果您从网址中删除"http://",那么您就是在本地磁盘上寻找一个名为"www.google.com"的文件。 - Rauli Rajande
1
这怎么会引起这么多关注和点赞呢?为什么要删除协议信息呢?即使在2008年,你也有FTP和HTTPS。 - Daniel W.
17个回答

-1

类似这样:

public function get($curl,$options){
    $context = stream_context_create($options);
    $file = @file_get_contents($curl, false, $context);
    $str1=$str2=$status=null;
    sscanf($http_response_header[0] ,'%s %d %s', $str1,$status, $str2);
    if($status==200)
        return $file        
    else 
        throw new \Exception($http_response_header[0]);
}

-2

我已经解决了所有问题,现在所有链接都可以正常工作。

public function getTitle($url)
    {
        try {
            if (strpos($url, 'www.youtube.com/watch') !== false) {
                $apikey = 'AIzaSyCPeA3MlMPeT1CU18NHfJawWAx18VoowOY';
                $videoId = explode('&', explode("=", $url)[1])[0];
                $url = 'https://www.googleapis.com/youtube/v3/videos?id=' . $videoId . '&key=' . $apikey . '&part=snippet';

                $ch = curl_init();

                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                curl_setopt($ch, CURLOPT_VERBOSE, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $response = curl_exec($ch);
                curl_close($ch);

                $data = json_decode($response);
                $value = json_decode(json_encode($data), true);

                $title = $value['items'][0]['snippet']['title'];
            } else {
                set_error_handler(
                    function () {
                            return false;
                    }
                );
                if (($str = file_get_contents($url)) === false) {
                    $title = $url;
                } else {
                    preg_match("/\<title\>(.*)\<\/title\>/i", $str, $title);
                    $title = $title[1];
                    if (preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $title))
                        $title = utf8_encode($title);
                    $title = html_entity_decode($title);
                }
                restore_error_handler();
            }
        } catch (Exception $e) {
            $title = $url;
        }
        return $title;
    }

1
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

-2
在使用file_get_contents()函数之前,您应该使用file_exists()函数。这样做可以避免php警告。
$file = "path/to/file";

if(file_exists($file)){
  $content = file_get_contents($file);
}

2
只有在调用本地文件并且您拥有检查本地文件是否存在的正确权限时,此方法才能正常工作。 - rubo77

-2
你可以使用这个脚本。
$url = @file_get_contents("http://www.itreb.info");
if ($url) {
    // if url is true execute this 
    echo $url;
} else {
    // if not exceute this 
    echo "connection error";
}

这里需要进行严格比较: if ($url === true)... 因为如果响应中返回了 0 或空值,就会引发连接错误。 - Daniel W.

-2
最简单的方法是在 file_get_contents 前面加上 @,例如:
$content = @file_get_contents($site); 

-4

这将尝试获取数据,如果失败,它将捕获错误并允许您在 catch 中执行任何需要的操作。

try {
    $content = file_get_contents($site);
} catch(\Exception $e) {
    return 'The file was not found';
}

-4
if (!file_get_contents($data)) {
  exit('<h1>ERROR MESSAGE</h1>');
} else {
      return file_get_contents($data);
}

1
不,你应该使用 === 进行条件检查,而不是 ==。 - Alp Altunel
3
不建议多次运行 file_get_contents 函数,一次足矣。 - Juakali92

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接