345

私はこのようなPHPコードを書きました

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

しかし、「http://」を削除すると$site、次の警告が表示されます。

警告: file_get_contents(www.google.com) [function.file-get-contents]: ストリームを開けませんでした:

試しtryてみcatchましたが、うまくいきませんでした。

4

18 に答える 18

565

Step 1: check the return code: if($content === FALSE) { // handle error here... }

Step 2: suppress the warning by putting an error control operator (i.e. @) in front of the call to file_get_contents(): $content = @file_get_contents($site);

于 2008-11-07T15:14:11.923 に答える
170

エラーハンドラーを、例外を呼び出す無名関数として設定し、その例外に対してtry/catchを使用することもできます。

set_error_handler(
    function ($severity, $message, $file, $line) {
        throw new ErrorException($message, $severity, $severity, $file, $line);
    }
);

try {
    file_get_contents('www.google.com');
}
catch (Exception $e) {
    echo $e->getMessage();
}

restore_error_handler();

1つの小さなエラーをキャッチするための多くのコードのように見えますが、アプリ全体で例外を使用している場合は、これを1回だけ実行する必要があります(たとえば、含まれている構成ファイルで)。全体を通して、すべてのエラーを例外に変換します。

于 2010-08-04T13:51:34.467 に答える
93

これを行う私のお気に入りの方法はかなり簡単です。

if (($data = @file_get_contents("http://www.google.com")) === false) {
      $error = error_get_last();
      echo "HTTP request failed. Error was: " . $error['message'];
} else {
      echo "Everything went better than expected";
}

上記の @enobrevを試した後にこれを見つけましたtry/catchが、これにより、コードが長くなりません (そして、IMO ではより読みやすくなります)。単純error_get_lastに最後のエラーのテキストを取得するために使用し、file_get_contents失敗すると false を返すので、単純な "if" でそれをキャッチできます。

于 2012-11-13T17:06:48.690 に答える
38

@ を前に付けることができます: $content = @file_get_contents($site);

これにより警告が抑制されます -慎重に使用してください! . エラー制御演算子を参照してください

編集:「http://」を削除すると、Web ページではなく、「www.google.....」というディスク上のファイルを探していることになります。

于 2008-11-07T15:13:51.313 に答える
25

1 つの代替方法は、エラーを抑制し、後でキャッチできる例外をスローすることです。これは、コード内に file_get_contents() への呼び出しが複数ある場合に特に便利です。それらすべてを手動で抑制して処理する必要がないからです。代わりに、1 つの try/catch ブロックでこの関数を複数回呼び出すことができます。

// Returns the contents of a file
function file_contents($path) {
    $str = @file_get_contents($path);
    if ($str === FALSE) {
        throw new Exception("Cannot access '$path' to read contents.");
    } else {
        return $str;
    }
}

// Example
try {
    file_contents("a");
    file_contents("b");
    file_contents("c");
} catch (Exception $e) {
    // Deal with it.
    echo "Error: " , $e->getMessage();
}
于 2011-06-24T04:17:00.403 に答える
16
function custom_file_get_contents($url) {
    return file_get_contents(
        $url,
        false,
        stream_context_create(
            array(
                'http' => array(
                    'ignore_errors' => true
                )
            )
        )
    );
}

$content=FALSE;

if($content=custom_file_get_contents($url)) {
    //play with the result
} else {
    //handle the error
}
于 2014-02-24T00:28:28.073 に答える
14

これが私がやった方法です... try-catchブロックは必要ありません... 最良の解決策は常に最も簡単です...お楽しみください!

$content = @file_get_contents("http://www.google.com");
if (strpos($http_response_header[0], "200")) { 
   echo "SUCCESS";
} else { 
   echo "FAILED";
} 
于 2009-03-06T05:11:17.760 に答える
4

最善の方法は、ファイルにログを記録したり、重要なものを電子メールで送信したりするなどの便利な独自のエラーおよび例外ハンドラーを設定することです。 http://www.php.net/set_error_handler

于 2008-11-07T16:57:28.483 に答える
-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]);
}
于 2019-04-23T16:36:32.967 に答える
-2

file_get_contents() を使用する前に、file_exists() 関数を使用する必要があります。このようにして、php 警告を回避できます。

$file = "path/to/file";

if(file_exists($file)){
  $content = file_get_contents($file);
}
于 2016-10-03T18:18:20.680 に答える
-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";
}
于 2012-02-27T07:57:12.027 に答える
-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;
    }
于 2021-10-09T09:12:24.083 に答える
-4

これはデータを取得しようとしますが、うまくいかない場合はエラーをキャッチし、キャッチ内で必要なことを何でもできるようにします。

try {
    $content = file_get_contents($site);
} catch(\Exception $e) {
    return 'The file was not found';
}
于 2016-07-28T16:37:04.193 に答える
-4
try {
   $site="http://www.google.com";
   $content = file_get_content($site);
   echo $content;
} catch (ErrorException $e) {
    // fix the url

}

set_error_handler(function ($errorNumber, $errorText, $errorFile,$errorLine ) 
{
    throw new ErrorException($errorText, 0, $errorNumber, $errorFile, $errorLine);
});
于 2016-12-14T08:50:33.820 に答える