我应该如何为 PHP 中的 HTTP 请求格式化 curl?
How should I format a curl for a HTTP request in PHP?
我知道有一个人(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'];
您提供的命令行将向远程服务器发送 GET - 但在您的代码中您发送 POST。注释掉 curl_setopt($ch1, CURLOPT_POST, 1);
,您的 PHP 代码将完全按照命令行执行。
您可以尝试使用这个 PHP 库 https://github.com/php-curl-class/php-curl-class。基本上它将所有 php curl 函数包装到 class。之后您可以轻松创建实现的模拟并编写像样的单元测试。
您的代码应如下所示:
<?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);
}
我知道有一个人(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'];
您提供的命令行将向远程服务器发送 GET - 但在您的代码中您发送 POST。注释掉 curl_setopt($ch1, CURLOPT_POST, 1);
,您的 PHP 代码将完全按照命令行执行。
您可以尝试使用这个 PHP 库 https://github.com/php-curl-class/php-curl-class。基本上它将所有 php curl 函数包装到 class。之后您可以轻松创建实现的模拟并编写像样的单元测试。
您的代码应如下所示:
<?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);
}