在宁静的笨消费卷曲
问题描述:
在纯PHP,我有一个使用REST式服务器这样的:在宁静的笨消费卷曲
$url = "http://localhost/pln/api/json?rayon=$rayon&id_pel=$id_pel&nama=$nama";
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
$respone = curl_exec($client);
$result = json_decode($respone);
我怎么能使用CodeIgniter的访问时,这样的卷曲?
答
你可以使用笨的默认curl库:
$this->load->library('curl');
$result = $this->curl->simple_get('http://example.com/');
var_dump($result);
更多详细信息请点击此链接: https://www.formget.com/curl-library-codeigniter/
答
有没有积极的cURL库周围笨3.x的有one for CI 2.x不再维护。
考虑使用Guzzle,这是非常流行的,并且被认为是PHP的事实上的HTTP接口库。下面是从文档的使用例子:
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
我还建议使用Requests这是由Python Requests模块的启发,比狂饮开始使用方式更容易:
$headers = array('Accept' => 'application/json');
$options = array('auth' => array('user', 'pass'));
$request = Requests::get('https://api.github.com/gists', $headers, $options);
var_dump($request->status_code);
// int(200)
var_dump($request->headers['content-type']);
// string(31) "application/json; charset=utf-8"
var_dump($request->body);
// string(26891) "[...]"
由于CodeIgniter 3.x has support for Composer包开箱即用,您可以通过作曲家轻松安装其中一个软件包,并立即开始使用它。
我强烈建议你不要去“下载脚本”方式建议在Manthan Dave's answer。 Composer为PHP提供了一个复杂的依赖管理生态系统;利用它! “下载这个脚本”的狗日子已经结束了。
答
我笨的卷曲URL中使用以下功能和工作正常进行配置,尝试一下:
function request($auth, $url, $http_method = NULL, $data = NULL) {
//check to see if we have curl installed on the server
if (!extension_loaded('curl')) {
//no curl
throw new Exception('The cURL extension is required', 0);
}
//init the curl request
//via endpoint to curl
$req = curl_init($url);
//set request headers
curl_setopt($req, CURLOPT_HTTPHEADER, array(
'Authorization: Basic ' . $auth,
'Accept: application/xml',
'Content-Type: application/x-www-form-urlencoded',
));
//set other curl options
curl_setopt($req, CURLOPT_RETURNTRANSFER, true);
curl_setopt($req, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($req, CURLOPT_TIMEOUT, 30);
//set http method
//default to GET if data is null
//default to POST if data is not null
if (is_null($http_method)) {
if (is_null($data)) {
$http_method = 'GET';
} else {
$http_method = 'POST';
}
}
//set http method in curl
curl_setopt($req, CURLOPT_CUSTOMREQUEST, $http_method);
//make sure incoming payload is good to go, set it
if (!is_null($data)) {
if (is_array($data)) {
$raw = http_build_query($data);
} else {
//Incase of raw xml
$raw = $data;
}
curl_setopt($req, CURLOPT_POSTFIELDS, $raw);
}
//execute curl request
$raw = curl_exec($req);
if (false === $raw) { //make sure we got something back
throw new Exception(curl_error($req) . $url, -curl_errno($req));
}
//decode the result
$res = json_decode($raw);
if (is_null($res)) { //make sure the result is good to go
throw new Exception('Unexpected response format' . $url, 0);
}
return $res;
}