How to use guzzle on codeigniter?

Member

by dedrick , in category: PHP CMS , 8 months ago

How to use guzzle on codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , 8 months ago

@dedrick 

To use Guzzle in CodeIgniter, you need to follow these steps:

  1. Install Guzzle using composer by running the following command in your CodeIgniter project directory:
1
composer require guzzlehttp/guzzle


  1. Create a new library file in the application/libraries directory of your CodeIgniter project and name it GuzzleHttpClient.php.
  2. Add the following code to the GuzzleHttpClient.php file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
require_once 'vendor/autoload.php';

use GuzzleHttpClient;

class GuzzleHttpClient {
    private $client;

    public function __construct() {
        $this->client = new Client();
    }

    public function get($url) {
        $response = $this->client->request('GET', $url);
        
        return $response->getBody()->getContents();
    }

    public function post($url, $data) {
        $response = $this->client->request('POST', $url, ['form_params' => $data]);
        
        return $response->getBody()->getContents();
    }

    // Add other HTTP methods as needed
}
?>


  1. Load the Guzzle library in your controller or model where you want to use it:
1
$this->load->library('GuzzleHttpClient');


  1. Use the GuzzleHttpClient methods to make HTTP requests:
1
2
$response = $this->guzzlehttpclient->get('https://jsonplaceholder.typicode.com/posts/1');
$data = json_decode($response);


You can now use Guzzle in your CodeIgniter project to make HTTP requests to external APIs or websites.