2017-03-01 32 views
0

我知道有個人製作的圖書館(https://github.com/tgallice/wit-php)。但是,我無法找到他如何格式化捲曲。我只想要做一個請求,所以使用他的庫會過度。我應該如何在PHP中爲HTTP請求設置curl格式?

下面是在終端工作的字符串,但我不知道如何用PHP編寫:curl -H 'Authorization: Bearer ACCESSCODE' 'https://api.wit.ai/message?v=20160526&q=mycarisbroken'

$ch1 = curl_init(); 
curl_setopt($ch1, CURLOPT_URL,"https://api.wit.ai/message?v=20160526&q=my%20car%20doesnt%20work"); 
curl_setopt($ch1, CURLOPT_POST, 1); 
// curl_setopt($ch1, CURLOPT_POSTFIELDS,$vars); //Post Fields 
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true); 

$headers = [ 
    'Authorization: Bearer ACCESSCODEOMITTED', 
]; 

curl_setopt($ch1, CURLOPT_HTTPHEADER, $headers); 
curl_setopt($ch1, CURLOPT_HEADER, true); 
curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, false); 
$server_output = curl_exec ($ch1); 
curl_close($ch1); 
Data::$answer = json_decode($server_output)['entities']['intent'][0]['value']; 
+0

退房[libcurl中(http://php.net/curl/) – hassan

+0

@HassanAhmed我不知道-H是什麼,所以該鏈接沒有多大幫助 – user7391050

+0

curl中的-H標誌表示您要發送到服務器的標頭 – hassan

回答

0

你給會GET發送到遠程服務器的命令行 - 但在你的您發送POST的代碼。註釋掉curl_setopt($ch1, CURLOPT_POST, 1);,你的PHP代碼將完成命令行的功能。

0

你可以嘗試使用這個PHP庫https://github.com/php-curl-class/php-curl-class。基本上它包裝了所有的php curl函數。之後你可以輕鬆地創建你的實現模擬,並寫出體面的單元測試。

您的代碼看起來應該是這樣的:

<?php 
$curl = new Curl(); 
$curl->setHeader('Authorization', 'Bearer ACCESSCODEOMITTED'); 
$curl->get('htps://api.wit.ai/message?v=20160526&q=mycarisbroken'); 

if ($curl->error) { 
    echo 'Error: ' . $curl->errorCode . ': ' . $curl->errorMessage . "\n"; 
} else { 
    echo 'Response:' . "\n"; 
    var_dump($curl->response); 
}