Proper way to send (POST) xml with guzzle 6
Asked Answered
R

6

22

I want to perform a post with guzzle sending an xml file. I did not find an example.

What I 've done so far is :

$xml2=simplexml_load_string($xml) or die("Error: Cannot create object");
use    GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
$client = new Client();
//
$request = new Request('POST', $uri, [ 'body'=>$xml]);
$response = $client->send($request);
 //
//$code = $response->getStatusCode(); // 200
//$reason = $response->getReasonPhrase(); // OK
 //
 echo $response->getBody();

No matter what I try I get back error -1 which means that xml is not valid. XML that I send passes online validation though and is valid %100

Please help.

Ruralize answered 11/1, 2016 at 16:32 Comment(0)
R
27

After some experiments, I have figured it out. Here is my solution in case someone reaches a dead end.

$request = new Request(
    'POST', 
    $uri,
    ['Content-Type' => 'text/xml; charset=UTF8'],
    $xml
);
Ruralize answered 12/1, 2016 at 8:53 Comment(0)
O
33

This is what worked for me on Guzzle 6:

// configure options
$options = [
    'headers' => [
        'Content-Type' => 'text/xml; charset=UTF8',
    ],
    'body' => $xml,
];

$response = $client->request('POST', $url, $options);
Obstacle answered 2/6, 2017 at 17:23 Comment(0)
R
27

After some experiments, I have figured it out. Here is my solution in case someone reaches a dead end.

$request = new Request(
    'POST', 
    $uri,
    ['Content-Type' => 'text/xml; charset=UTF8'],
    $xml
);
Ruralize answered 12/1, 2016 at 8:53 Comment(0)
S
3

If you want to send xml using the post method, here is an example:

$guzzle->post($url, ['body' => $xmlContent]);
Savell answered 24/10, 2016 at 11:47 Comment(0)
H
3

You can do that in a below way

$xml_body = 'Your xml body';
$request_uri = 'your uri'
$client = new Client();
$response = $client->request('POST', $request_uri, [
              'headers' => [
                 'Content-Type' => 'text/xml'
               ],
              'body'   => $xml_body
            ]);
Heeled answered 9/8, 2019 at 8:46 Comment(0)
B
0

I found I also had to trim the body - there was a leading new line character in the body text, and Guzzle refused to send the body at all until I trimmed it.

Bagdad answered 16/9, 2021 at 8:14 Comment(0)
M
-3

Try posting the data like:

$xml2=simplexml_load_string($xml) or die("Error: Cannot create object");
use    GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
$client = new Client();
//
$request = new Request('POST', $uri, [
'form_params' => [
        'xml' => $xml,
    ]
]);
$response = $client->send($request);
//$code = $response->getStatusCode(); // 200
//$reason = $response->getReasonPhrase(); // OK
echo $response->getBody();
Morton answered 11/1, 2016 at 17:16 Comment(1)
Thanks for the suggestion but it does not work. Again the same response. Is there any documentation describing in detail the options object?Ruralize

© 2022 - 2025 — McMap. All rights reserved.