首页 > 解决方案 > 返回状态为400时使用phps file_get_contents获取服务器发送的内容

问题描述

我正在使用 phpsfile_get_contents连接我的 API 服务器。当服务器返回 200 状态时它运行良好(它从 api 服务器返回内容)。问题是当 api 服务器返回 400 状态时。如果 api 服务器返回 400 状态,该函数只返回 FALSE(不是内容)。
这是我从$http_response_header得到的

[ "HTTP\/1.1 400 Bad Request", 
"Server: nginx\/1.16.1", 
"Date: Fri, 06 Nov 2020 05:39:09 GMT", 
"Content-Type: application\/json", 
"Content-Length: 117", 
"Connection: close", 
"Strict-Transport-Security: max-age=31536000; includeSubDomains; preload", 
"Access-Control-Allow-Origin: *", 
"Access-Control-Expose-Headers: Content-Length,Content-Type,Date,Server,Connection" ]

现在我的问题是,当状态为 400 时,如何获取从API 服务器发送的内容?

标签: php

解决方案


您可以使用 curl 而不是file_get_contents因为它对错误处理有更好的支持:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "{url}"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$output = curl_exec($ch);   

// handle any other code than 200
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
    // your handling code
    print_r($output);
}

curl_close($ch);

推荐阅读