在打印之前检查file_get_contents是否返回

时间:2018-01-23 15:12:17

标签: php mysql json web-services php-7

所以我在环境中无法使用curl所以经过一些研究后我发现我可以file_get_contents使用stream_context_create上下文。

它工作得很好但是我注意到如果请求失败file_get_contents返回false,我想打印一个指示错误的JSON对象而不是普通false

以下是我的代码片段:

$postdata = http_build_query(
    $_POST
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context = stream_context_create($opts);

echo file_get_contents($urlAtividade, false, $context);

我用它来从另一个WEBService获取数据。我担心的是,有些请求确实有很大的输出,所以我想知道检查这个问题的最佳方法是什么。

我想知道如果我将返回值保存在变量中,file_get_contents返回的内存是否会加倍?因为我最关心的是创造开销或耗尽内存。

$return = file_get_contents($urlAtividade, false, $context);

if($return === FALSE){
    $response["error"] = TRUE;
    $response["error_msg"] = "Request Failed";
    echo json_encode($response);
}
else {
    echo $return;
}

我想知道是否有办法打印结果并在if语句中返回false?

1 个答案:

答案 0 :(得分:1)

我认为你不必担心这个问题。

为变量赋值不会复制它,它只是创建对同一内存的引用。只有在您修改其中一个时才会复制。

如果您想避免将内容复制到内存中,则必须使用readfile()而不是file_get_contents()。这会将内容直接复制到PHP输出缓冲区中,当缓冲区已满时,会定期刷新(除非您已打开输出缓冲以便捕获它)。但是,如果你这样做,那么你将无法首先检查该值。