kate_hudson kate_hudson - 1 year ago 128
PHP Question

Replicating cURL post in Guzzle

I was using cURL for posting data to an API but have decided to switch to Guzzle. Using cURL I would do this

$data =

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.someurl.com/lead.api/add?apiKey=12345&accountKey=12345");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/xml',
'Content-Length: ' . strlen($data)

$output = curl_exec($ch);

This is what I am currently attempting with Guzzle.

$data = "<Lead>

$client = new GuzzleHttp\Client();
$req = $client->request('POST', 'https://somurl', [
'body' => $data,
'headers' => [
'Content-Type' => 'text/xml',
'Content-Length' => strlen($data),
$res = $client->send($req);
$output = $res->getBody()->getContents();

The first problem I am facing is that it is stating that arguement 3 for request needs to be an array, and I am passing it a string. Thats fine, but then how can I send my xml block? Additionally, I think I may have set the headers incorrectly?

I have gone through the documentation and see that parameter 3 needs to be an array, but I do not see how to post an XML string.

Any advice appreciated.


Answer Source

You can create an array using the 'body' param:

$client->request('POST', 'http://whatever', ['body' => $data]);

Read more at: http://docs.guzzlephp.org/en/latest/quickstart.html?highlight=post#post-form-requests

To set headers, you can do something like:

$response = $client->request('POST', 'http://whatever', [
    'body' => $data,
    'headers' => [
        'Content-Type' => 'text/xml',
        'Content-Length' => strlen($data),
$output = $response->getBody()->getContents();

Read more at: http://docs.guzzlephp.org/en/latest/request-options.html#headers