PHP文件通过404获取内容

PHP文件通过404获取内容,php,arrays,json,Php,Arrays,Json,我正在获取包含文件内容的JSON数组,但是如果页面不存在,我想给出一条消息:找不到播放器。但现在我得到了这个错误: 警告:文件获取内容(urlwithan404errorhere) [function.file get contents]:无法打开流:HTTP请求 失败!在中找不到HTTP/1.1 404------- 当api给我一个正确的JSON数组时,我没有得到这个错误 这是使用的代码: $gegevens = file_get_contents(''); $array_2 =

我正在获取包含
文件内容的JSON数组,但是如果页面不存在,我想给出一条消息:找不到播放器。但现在我得到了这个错误:

警告:文件获取内容(urlwithan404errorhere) [function.file get contents]:无法打开流:HTTP请求 失败!在中找不到HTTP/1.1 404-------

当api给我一个正确的JSON数组时,我没有得到这个错误

这是使用的代码:

$gegevens = file_get_contents('');      
$array_2 = json_decode($gegevens, TRUE);
$summonerid = $array_2[$naam]["id"];

您的代码可能会变成这样:

$gegevens = @file_get_contents('');      

if ($gegevens !== FALSE) {
    $array_2 = json_decode($gegevens, TRUE);
    $summonerid = $array_2[$naam]["id"];
} else {
    $summonerid = 0;
}
if (($gegevens = @file_get_contents('')) === false) {
    printf("<h1>Player not found!</h1>\n");
    return;
}

// ... continue here ...
解释:
*如果请求失败,
文件获取内容前面的
@
将停止显示php错误。

*如果
$calleerid
等于
0
,则您找不到玩家

请尝试以下操作:

$gegevens = @file_get_contents('');      

if ($gegevens !== FALSE) {
    $array_2 = json_decode($gegevens, TRUE);
    $summonerid = $array_2[$naam]["id"];
} else {
    $summonerid = 0;
}
if (($gegevens = @file_get_contents('')) === false) {
    printf("<h1>Player not found!</h1>\n");
    return;
}

// ... continue here ...
if($gegevens=@file\u get\u contents(“”))==false){
printf(“未找到播放器!\n”);
返回;
}
// ... 继续这里。。。

如果
文件获取内容()失败,
@
将禁止显示任何错误消息。在这种情况下,它将返回
false
(使用
==
进行比较,以避免与空文件混淆),您可以使用它进行故障检测。

如果您计划大量使用服务,我建议您查看guzzle,而不是对文件内容进行此类检查。您将获得更干净、更好的代码。我只使用了一次,所以不用了,谢谢:d此主题已经发布: