Proper way to send (POST) xml with guzzle 6

2020-06-08 04:36发布

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.

5条回答
时光不老,我们不散
2楼-- · 2020-06-08 04:41

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

$guzzle->post($url, ['body' => $xmlContent]);
查看更多
唯我独甜
3楼-- · 2020-06-08 04:43

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);
查看更多
ゆ 、 Hurt°
4楼-- · 2020-06-08 04:45

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
);
查看更多
5楼-- · 2020-06-08 04:59

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();
查看更多
孤傲高冷的网名
6楼-- · 2020-06-08 05:06

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
            ]);
查看更多
登录 后发表回答