ここにPHP関数があります:
function TryGetJSON($URL) { //Attempts to retrieve the JSON at a URL, script terminates if failure
function LogAndDie($msg) { error_log($msg); die(); }
for($attempt = 0; $attempt < 3; $attempt++) { //Try 3 times to fetch URL
$JSON = file_get_contents($URL); //Attempt to fetch, then check Response Header
if( !$JSON && isset($http_response_header) && strstr($http_response_header[0], '503'))
continue; //503 response: server was busy, so try again
else
break; //$JSON is populated, must be a 200 response
}//$JSON is always false on 404, file_get_contents always returns false on read failure
if(isset($http_response_header)) {
if(strstr($http_response_header[0], '503')) //If still 503, then all our attempts failed
LogAndDie('Could not get JSON file (' . $URL . '): ' . $http_response_header[0] . ' after 3 attempts.');
if(!strstr($http_response_header[0], '200')) //If not a 200
LogAndDie('Could not get JSON file (' . $URL . '): ' . $http_response_header[0]);
if(!strstr($http_response_header[7], 'application/json') ) //Check Correct Content-Type
LogAndDie('Wrong Content Type for (' . $URL . '). Received: ' . $http_response_header[7]);
return $JSON;
}
if(!$JSON) LogAndDie('Could not get JSON file (' . $URL . ').'); //Catch all
}
関数の要点は、指定されたURLからJSONを取得できなかった場合に、関数die()に書き込みを行うことです。error_logの場合、3回再試行し503ます。
私はそれに関していくつかの主な質問があります:
GETリクエストの
Content-Typeインデックスが常に7であるとは限らないため、チェックは常に正しいとは限りません。forで全体をループして$http_response_headerチェックすることになっていますか?私には不器用なようです。マニュアルページには、これについてほとんど何もありませんでした。それを処理するためのより簡単な方法が必要ですか?strstrContent-Type私
error_logはこのような行を持っています404:
[25-Oct-2012 09:02:23] PHP Warning: file_get_contents(...) [<a href='function.file-get-contents'>function.file-get-contents</a>]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in ... on line 8
[25-Oct-2012 09:02:23] Could not get JSON file (...): HTTP/1.1 404 Not Found
私は自分の(2行目)を維持することにのみ興味があり、error_log両方で満たすことには興味がありません。@でこれを抑制するために使用できることがわかりましfile_get_contentsたが、それは私が予測できないことについて知る必要があるかもしれない他の警告を抑制するかもしれません。この関数でその特定の警告を抑制する方法はありますか?