我应该如何在PHP中格式化HTTP请求的curl?

时间:2017-03-01 19:30:30

标签: php curl wit.ai

我知道有个人(https://github.com/tgallice/wit-php)制作的图书馆。但是,我无法找到他如何格式化卷曲。我只想做一个请求,所以使用他的库会有点过分。

这是在终端中工作的字符串,但我不确定如何用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'];

2 个答案:

答案 0 :(得分:0)

您提供的命令行将向远程服务器发送GET - 但在您的代码中,您发送了一个POST。注释掉curl_setopt($ch1, CURLOPT_POST, 1);,您的PHP代码将完全按命令行执行。

答案 1 :(得分: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);
}