REMEMBER PHP

MINTE9
2REMEMBER




Last update:   23-07-2021

Guzzle

Guzzle is a HTTP client library for PHP, initially a wrapper library around cURL. It evolved to a transport agnostic PSR-7 compatible library. It is shipped on Packagist as a Composer package. You can specify Guzzle as a dependency in your project's existing composer.json. file: Install in an existing project.
 
{
   "require": {
      "guzzlehttp/guzzle": "~6.0"
   }
}
... 2 more rows
˄˄˄
 
// mkdir composer-guzzle

composer require guzzlehttp/guzzle:~6.0
 
// index.php

require __DIR__ . '/vendor/autoload.php';

$client = new \GuzzleHttp\Client();

$response = $client->request('GET', 'http://httpbin.org/get');

$json = json_decode($response->getBody());

echo $json->origin; //188.25.59.99
... 3 more rows
˄˄˄

External API

Using Guzzle with an external API.
 CodeCopy

require __DIR__ . '/vendor/autoload.php';

$client = new \GuzzleHttp\Client(); // Look Here

$url = "https://currency-converter5.p.rapidapi.com/currency/convert?format=json&from=USD&to=RON&amount=1"';

$request = $client->request('GET', $url, [
"debug" => false,
"headers" => [
  "x-rapidapi-host" => "currency-converter5.p.rapidapi.com",
  "x-rapidapi-key" => "xxx"
]
]);

$json = json_decode($request->getBody());
var_dump($json);
... 9 more rows
˄˄˄

Guzzle vs cURL

The main benefits of using Guzzle over cURL is the API it offers. Result is more concise and readable code. Guzzle is an abstraction layer for http request. It uses cURL by default you can use any other http client that you want.

More examples

 
require __DIR__ . '/vendor/autoload.php';

$client = new \GuzzleHttp\Client();

$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');

$json = json_decode($response->getBody());

echo $json->full_name; // guzzle/guzzle
... 2 more rows
˄˄˄
 
require __DIR__ . '/vendor/autoload.php';

$client = new \GuzzleHttp\Client();

// Send an asynchronous request.

$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');

$promise = $client->sendAsync($request)->then(function ($response) {
  echo 'I completed! ' . $response->getBody();
});
$promise->wait();
... 5 more rows
˄˄˄

Questions    
No. 78   Autoloader
CARD
77
96

        A B C D E F
🔔
1/2