php - 文件获取内容 : get full response even on error

标签 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);

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

最佳答案

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

'ignore_errors' => true

所以你会得到

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

关于php - 文件获取内容 : get full response even on error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18513462/

相关文章:

php - MariaDB 避免死锁

sql-server - 如何为不同的数据库分隔用户定义的消息

php - 如何在 PHP 中获取文件的内容类型?

php - 从子方法访问时,父方法设置的父类属性为空

php - Laravel 5 项目导致 PHP/Apache 崩溃

php - 使用 PHP 将数字缩写(5.2k、1.7m 等)转换为有效整数

php - 引用 - 这个错误在 PHP 中意味着什么?

c - 如果失败则返回错误的函数

javascript - PHP 脚本未在服务器 shell 上显示正确的数据

php - 为 file_get_contents 清理用户提供的 URL