file_get_contents:即使出错也会得到完整的响应

hou*_*oft 6 php error-handling file-get-contents

file_get_contents即使发生错误,是否可以向我显示实际响应?

否则很难调试.例如,假设您有以下代码:

$url = 'https://api.twitter.com/oauth/request_token';
$data = array();

$options = array(
    'http' => array(
    'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
    'method'  => 'POST',
    'content' => http_build_query($data),
    ),
);
$context  = stream_context_create($options);
$result = @file_get_contents($url, false, $context);

var_dump($result);
var_dump($http_response_header);
Run Code Online (Sandbox Code Playgroud)

这显示结果和HTTP标头的NULL,但我想获得Twitter发回的实际消息(应该是类似的Failed to validate oauth signature and token),这是你尝试https://api.twitter.com/oauth/request_token在浏览器中加载时得到的.

nva*_*sch 6

上下文有一个非常简单的开关.只需将此行添加到选项:

'ignore_errors' => true
Run Code Online (Sandbox Code Playgroud)

所以你会得到的

$options = array(
    'http' => array(
    'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
    'method'  => 'POST',
    'content' => http_build_query($data),
    'ignore_errors' => true
    )
);
Run Code Online (Sandbox Code Playgroud)