user3384985 user3384985 - 4 months ago 74
PHP Question

pecl_http add post request body in hotelbeds apitude

Recently I started working with hotelbeds apitude PHP API

I am trying to add

xml
code to a
POST
request body using
pecl_http
. I tried with following code -

$xml_part = <<< EOD
<<<XML PART>>> EOD;

$request = new http\Client\Request("POST",
$endpoint,
["Api-Key" => $hotel_beds_config['api_key'],
"X-Signature" => $signature,
"Content-Type" => "application/xml",
"Accept" => "application/xml"],
$xml_part
);


I got the following error


Fatal error: Uncaught TypeError: Argument 4 passed to http\Client\Request::__construct() must be an instance of http\Message\Body, string
given


Then I tried with following code -

$request = new http\Client\Request("POST",
$endpoint,
["Api-Key" => $hotel_beds_config['api_key'],
"X-Signature" => $signature,
"Content-Type" => "application/xml",
"Accept" => "application/xml"],
new http\Message\Body($xml_part)


Now I get following error -


Fatal error: Uncaught http\Exception\InvalidArgumentException: http\Message\Body::__construct() expects parameter 1 to be resource, string given


I get the documentation to add body message here -

pecl_http

How can I add the xml code to the
POST
request?

Answer

According to the http\Message\Body::__construct() constructor documentation, the single parameter it optionally accepts is a stream or file handle resource (as in fopen()). It does not directly accept string data as you ave provided in $xml_part.

Instead, pecl http provides an append() method on the Body class which you should be able to use to append the XML onto the empty body. So start by creating a Body object in a variable, then append your XML onto it. Finally, pass the Body object into your Request object.

// Create a Body object first, with no argument
$body = new http\Message\Body();
// Append your XML to it
$body->append($xml_part);

// Create the Request and pass $body to it
$request = new http\Client\Request("POST",
                $endpoint,
                ["Api-Key" => $hotel_beds_config['api_key'],
                    "X-Signature" => $signature,
                    "Content-Type" => "application/xml",
                    "Accept" => "application/xml"],
                // Pass in $body
                $body
            );

// Create an \http\Client object, enqueue, and send the request...
$client = new \http\Client();
// Set options as needed for your application...
$client->enqueue($request);
$client->send();

Addendum: Why not use the SDK?

The API you are attempting to POST to provides a PHP SDK. If the SDK supports the Availability function you are hoping to use, perhaps it would be simpler to use it rather than pecl_http (which has limited documentation). The SDK would then abstract all of the HTTP messaging into a series of PHP methods and properties, eliminating any doubt on the proper construction of POST requests.

Comments