PHP Get Content of HTTP 400 Response

2019-01-11 19:52发布

I am using PHP with the Amazon Payments web service. I'm having problems with some of my requests. Amazon is returning an error as it should, however the way it goes about it is giving me problems.

Amazon returns XML data with a message about the error, but it also throws an HTTP 400 (or even 404 sometimes). This makes file_get_contents() throw an error right away and I have no way to get the content. I've tried using cURL also, but never got it to give me back a response.

I really need a way to get the XML returned regardless of HTTP status code. It has an important "message" element that gives me clues as to why my billing requests are failing.

Does anyone have a cURL example or otherwise that will allow me to do this? All my requests currently use file_get_contents() but I am not opposed to changing them. Everyone else seems to think cURL is the "right" way.

2条回答
趁早两清
2楼-- · 2019-01-11 20:11

You have to define custom stream context (3rd argument of function file_get_contents) with ignore_errors option on.

查看更多
甜甜的少女心
3楼-- · 2019-01-11 20:17

As a follow-up to DoubleThink's post, here is a working example:

$url = 'http://whatever.com';

//Set stream options
$opts = array(
  'http' => array('ignore_errors' => true)
);

//Create the stream context
$context = stream_context_create($opts);

//Open the file using the defined context
$file = file_get_contents($url, false, $context);
查看更多
登录 后发表回答