2016-08-13 59 views
1

我使用cURL將數據發佈到API,但決定切換到Guzzle。使用捲曲我會這樣做在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); 

這就是我目前正在嘗試與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(); 

我面臨的第一個問題是,它是指出arguement 3請求需要是一個數組,並且我傳遞它的字符串。這很好,但那我怎麼發送我的xml塊呢?另外,我想我可能會錯誤地設置標題?

我已經通過文檔,看到參數3需要是一個數組,但我不知道如何發佈一個XML字符串。

任何意見讚賞。

感謝

+0

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

+0

完美,謝謝。標記爲答案,我會接受。你知道我可以如何設置標題嗎?# –

回答

3

您可以使用的 '身體' PARAM數組:

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

更多詳情: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(); 

閱讀更多的:http://docs.guzzlephp.org/en/latest/request-options.html#headers

+0

我正在嘗試類似的東西,但我得到類型錯誤:參數1傳遞給GuzzleHttp \ Client :: send()必須實現接口Psr \ Http \ Message \ RequestInterface –

+0

@kate_hudson顯示你正在嘗試的代碼。 –

+0

沒問題,我已經更新了操作。 –