【问题标题】:Proper way to send (POST) xml with guzzle 6使用 guzzle 6 发送 (POST) xml 的正确方法
【发布时间】:2016-04-16 01:21:51
【问题描述】:

我想用 guzzle 发送一个 xml 文件来执行一个帖子。我没有找到示例。

到目前为止我所做的是:

$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();

无论我尝试什么,我都会返回错误 -1,这意味着 xml 无效。 我发送的 XML 通过了在线验证并且有效 %100

请帮忙。

【问题讨论】:

    标签: php xml guzzle guzzle6


    【解决方案1】:

    尝试发布如下数据:

    $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();
    

    【讨论】:

    • 感谢您的建议,但它不起作用。又是同样的反应。是否有任何文档详细描述了选项对象?
    【解决方案2】:

    经过一些实验,我想通了。这是我的解决方案,以防有人走到死胡同。

    $request = new Request(
        'POST', 
        $uri,
        ['Content-Type' => 'text/xml; charset=UTF8'],
        $xml
    );
    

    【讨论】:

      【解决方案3】:

      如果你想使用 post 方法发送 xml,这里是一个例子:

      $guzzle->post($url, ['body' => $xmlContent]);
      

      【讨论】:

        【解决方案4】:

        这就是在 Guzzle 6 上对我有用的方法:

        // configure options
        $options = [
            'headers' => [
                'Content-Type' => 'text/xml; charset=UTF8',
            ],
            'body' => $xml,
        ];
        
        $response = $client->request('POST', $url, $options);
        

        【讨论】:

          【解决方案5】:

          您可以通过以下方式做到这一点

          $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
                      ]);
          

          【讨论】:

            【解决方案6】:

            我发现我还必须修剪正文 - 正文中有一个前导换行符,Guzzle 拒绝发送正文,直到我修剪它。

            【讨论】:

              猜你喜欢
              • 2020-11-08
              • 1970-01-01
              • 2016-02-14
              • 1970-01-01
              • 2015-08-31
              • 2019-10-12
              • 2018-07-18
              • 2014-07-17
              • 2017-04-21
              相关资源
              最近更新 更多