haukurh / curl
cURL library wrapper to simplify the usage of cURL requests.
1.4.1
2021-12-10 14:30 UTC
Requires
- php: >=7.1
- ext-curl: *
- ext-json: *
README
A simple PHP library wrapper for cURL to simplify the usage of cURL requests.
Basic usage
<?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
Every request made returns an instance of Response class, which has some useful methods to work with.
$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
Set some options
Common cURL options have been made available to configure through some methods
$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 }
or if you're more comfortable with good ol' way of configuring 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 }
you can also set cURL options per request
$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 }