kate_hudson kate_hudson - 3 months ago 36
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 =
"<Lead>
<Name>$newProject->projectName</Name>
<Description>$newProject->projectName</Description>
<EstimatedValue>$newProject->projectValue</EstimatedValue>
</Lead>";

$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>
<Name>$campaign->campaignName</Name>
<Description>$campaign->campaignName</Description>
<EstimatedValue>$campaign->campaignValue</EstimatedValue>
</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.

Thanks

Answer

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