To make an HTTP POST request with Guzzle in PHP, you can follow these steps:
Install Guzzle:
composer require guzzlehttp/guzzle
.Include the Guzzle library in your PHP file:
require_once 'vendor/autoload.php';
Use Guzzle to make the POST request:
use GuzzleHttp\Client;
// Create an instance of Guzzle HTTP client
$client = new Client();
// Set the request URL endpoint and options
$url = "http://example.com/api/endpoint";
$options = [
'json' => [
'key1' => 'value1',
'key2' => 'value2'
]
];
// Send POST request using Guzzle
$response = $client->post($url, $options);
// Get the response body
$body = $response->getBody();
// Optionally, convert the response body to JSON
$jsonData = json_decode($body, true);
// Process the response
// ...
In the above example, replace the $url
with the actual URL endpoint you want to send the POST request to. The $options['json']
array contains the data to be sent in the POST request body.
Handle the response as needed:
You can access the response body using $response->getBody()
. You can also convert the response body to JSON using json_decode($body, true)
to work with it as an associative array.
Remember to handle any exceptions that may be thrown during the request process to ensure proper error handling.
That's it! You have successfully made an HTTP POST request using Guzzle in PHP.