在 Guzzle 中复制 cURL 帖子

kat*_*son 3 php guzzle laravel-5.2

我使用 cURL 将数据发布到 API,但已决定切换到 Guzzle。使用 cURL 我会这样做

$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);
Run Code Online (Sandbox Code Playgroud)

这就是我目前正在尝试使用 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();
Run Code Online (Sandbox Code Playgroud)

我面临的第一个问题是,它声明请求的论证 3 需要是一个数组,而我将它传递给一个字符串。那很好,但是我怎样才能发送我的 xml 块呢?另外,我想我可能错误地设置了标题?

我已经阅读了文档并看到参数 3 需要是一个数组,但我不知道如何发布 XML 字符串。

任何建议表示赞赏。

谢谢

Neh*_*ani 7

您可以使用“body”参数创建一个数组:

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

阅读更多信息:http : //docs.guzzlephp.org/en/latest/quickstart.html?highlight=post#post-form-requests

要设置标题,您可以执行以下操作:

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

阅读更多信息:http : //docs.guzzlephp.org/en/latest/request-options.html#headers