简体   繁体   English

在Guzzle中复制cURL发布

[英]Replicating cURL post in Guzzle

I was using cURL for posting data to an API but have decided to switch to Guzzle. 我使用cURL将数据发布到API,但决定切换到Guzzle。 Using cURL I would do this 使用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);

This is what I am currently attempting with Guzzle. 这就是我目前正在尝试使用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. 我面临的第一个问题是,它表明请求的论据3必须是一个数组,而我正在将其传递给一个字符串。 Thats fine, but then how can I send my xml block? 很好,但是那我该如何发送xml块呢? 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. 我浏览了文档,看到参数3需要是一个数组,但是我看不到如何发布XML字符串。

Any advice appreciated. 任何建议表示赞赏。

Thanks 谢谢

You can create an array using the 'body' param: 您可以使用'body'参数创建数组:

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

Read more at: http://docs.guzzlephp.org/en/latest/quickstart.html?highlight=post#post-form-requests 有关更多信息,请访问: 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 有关更多信息,请访问: http : //docs.guzzlephp.org/en/latest/request-options.html#headers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM