PHP Get Content of HTTP 400 Response
Asked Answered
M

2

11

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.

Macon answered 14/9, 2010 at 15:2 Comment(0)
G
20

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

Goar answered 14/9, 2010 at 15:9 Comment(1)
Ahh! It's so simple and it works! Thanks for the help. I could have figured this out if it wasn't so obscure.Macon
M
18

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);
Macon answered 14/9, 2010 at 15:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.