2017-02-21 183 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