haukurh / curl
cURL 库包装器,简化 cURL 请求的使用。
1.4.1
2021-12-10 14:30 UTC
Requires
- php: >=7.1
- ext-curl: *
- ext-json: *
README
一个简单的 PHP 库包装器,简化 cURL 请求的使用。
基本使用
<?php require 'vendor/autoload.php'; use Haukurh\Curl\Curl; $curl = new Curl(); $response = $curl->get("http://example.com/feed.xml"); if ($response->isOk()) { $xml = $response->body(); // Do something with the XML } // Post something $fields = [ 'title' => 'Some article title', 'content' => 'Some silly example content', ]; $postResponse = $curl->post("http://example.com/article/new", $fields); if ($response->isSuccessful()) { // Be happy you post request was successful }
响应
每个请求都会返回一个 Response 类的实例,该类提供一些有用的方法来处理。
$curl = new Curl(); $response = $curl->get("http://example.com/feed.xml"); echo $response->url(); // "http://example.com/feed.xml" echo $response->code(); // 200 echo $response->isOk(); // true echo $response->contentType(); // text/xml; echo $response->size(); // 3510 $body = $response->body(); $json = $response->json(); // Json payload as ?stdClass $array = (array)$response->json(); // Json as an array
设置一些选项
常见的 cURL 选项已经通过一些方法提供,以便进行配置
$curl = new Curl(); $curl->setTimeout(3); $curl->setFollowLocation(true); $curl->setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'); $response = $curl->get("http://example.com/feed.xml"); if ($response->isOk()) { $xml = $response->body(); // Do something with the XML }
或者如果您更习惯于传统的 cURL 配置方式
$curl = new Curl([ CURLOPT_TIMEOUT => 3, CURLOPT_FOLLOWLOCATION => true, CURLOPT_USERAGENT => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36', ]); $response = $curl->get("http://example.com/feed.xml"); if ($response->isOk()) { $xml = $response->body(); // Do something with the XML }
您也可以为每个请求设置 cURL 选项
$curl = new Curl(); $options = [ CURLOPT_TIMEOUT => 3, CURLOPT_FOLLOWLOCATION => true, CURLOPT_USERAGENT => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36', ]; $response = $curl->request("http://example.com/feed.xml", $options); if ($response->isOk()) { $xml = $response->body(); // Do something with the XML }