2017-02-21 78 views
0

我很努力地在PHP中使用cURL。我不知道我需要做些什麼來「翻譯」這個:「翻譯」cURL到PHP

curl -X POST -u "{username}:{password}" --header "Content-Type: application/json" --data-binary @profile.json "https://gateway.watsonplatform.net/personality-insights/api/v3/profile?version=2016-10-20&consumption_preferences=true&raw_scores=true" 

進入PHP在那裏執行它。

這一切到目前爲止,我已經得到了,但我感覺好像我還差得遠:

$url2 = 'https://watson-api-explorer.mybluemix.net/personality-insights/api/v3/profile?raw_scores=false&csv_headers=false&consumption_preferences=true&version=2017-02-01'; 
$request_headers = array(); 
$request_headers[] = 'Accept: application/json'; 
$request_headers[] = 'Content-Type: text/plain'; 
$request_headers[] = 'Content-Language: en'; 
$request_headers[] = 'Accept-Language: en'; 

$ch2 = curl_init($url2); 
curl_setopt($ch2, CURLOPT_POST, 1); 
curl_setopt($ch2, CURLOPT_POSTFIELDS, $myvars2); 
curl_setopt($ch2, CURLOPT_FOLLOWLOCATION, 1); 
curl_setopt($ch2, CURLOPT_HEADER, $request_headers); 
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1); 
$response2 = curl_exec($ch2); 
var_dump($response2); 
+1

其實你是非常接近。你只是缺少我所看到的驗證片。你從上面的腳本得到了什麼輸出? – JakeParis

+0

這就是我認爲我被卡住的地方。我不知道'-u'是什麼,以及如何將它「翻譯」爲PHP。我想出了標題,但這就是它 – jonmrich

回答

3

看起來你只是缺少認證件:

curl_setopt($ch2, CURLOPT_USERPWD, "yourUsername:yourPassword"); 

查看manual。此外,你可以這樣做,這可以更容易一些:

curl_setopt_array($ch2, array(
    CURLOPT_POST => 1, 
    CURLOPT_POSTFIELDS => $myvars2, 
    CURLOPT_FOLLOWLOCATION => 1, 
    CURLOPT_HEADER => $request_headers, 
    CURLOPT_RETURNTRANSFER => 1, 
    CURLOPT_USERPWD => 'yourUsername:yourPassword' 
); 
+0

超級有用......謝謝。我現在已經過身份驗證,但我必須錯誤地傳遞數據。這是我需要的第一位:'curl -X POST -header'Content-Type:text/plain'--header'Accept:application/json'--header'Content-Language:en'--header 'Accept-Language:en'-d'一堆普通文本在這裏'我除了'-d'部分外都有其他東西。這是什麼「命令」? – jonmrich

+0

這裏是你的-d:https://curl.haxx.se/docs/manpage.html#-d – JakeParis

+0

@jonmrich你需要通過該參數發送什麼? – JakeParis