I am using BOTH Guzzle and Codeigniter 3.0 for the first time. Also I admit I am using php namespace for the first time.
I am trying to make a very simple get request using Guzzle according to the examples provided in the docs. (The Guzzle docs say nothing about codeigniter).
The Guzzle files are located at application/class/guzzle
Here is my very simple controller
public function indey () {
$data = array();
$data['main_content'] = "hiview";
$data['title'] = "Data Analyzer - Welcome";
$data['xas'] = $this->guzzler();
$this->load->view('template', $data);
}
private function guzzler() {
$client = new GuzzleHttp\Client;
$response = $client->get('http://guzzlephp.org');
return $response;
}
This is my simple view
<div class="row">
<div class="col-xs-12">
<h1>Hi</h1>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<h1><?php var_dump($xas); ?></h1>
</div>
</div>
This is the error I am getting
A PHP Error was encountered Severity: Error Message: Class 'GuzzleHttp\Client' not found Filename: controllers/hello.php Line Number: 22 Backtrace:
In application/config/config.php
$config['composer_autoload'] = FCPATH.'vendor/autoload.php';
it work fine for me
You should load it in your controller methods where needed or if desired, autoload it. I use the former: First: use install it using composer in the application folder:
composer require guzzlehttp/guzzle:~6.0
Second: Let CI autoload composer (applications/config/config.php)
$config['composer_autoload'] = TRUE;
Then in your controller
public function guzzler_get($url, $uri)
{
$client = new GuzzleHttp\Client(['base_uri' => $url]);
$response = $client->get($uri);
// print_r($response); // print out response
// print out headers:
// foreach ($response->getHeaders() as $name => $values) {
// echo $name . ': ' . implode(', ', $values) . "\r\n";
// }
return $response;
}
Use:
$your_var = $this->guzzler_get('http://httpbin.org', '/html');
You now have the response in the $your_var
variable. For the rest, check the documentation. Otherwise use a "friendlier" method/library for your http requests like CodeIgniter-cURL or Requests
I solved adding following instruction at the beginning of my .php file:
require 'C:/php/vendor/autoload.php';
but I'm not sure it's a good practice...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With