To send data as JSON in a Guzzle POST request in PHP, you can use the json
option provided by Guzzle. Here's an example:
use GuzzleHttp\Client;
$client = new Client();
$body = [
'key1' => 'value1',
'key2' => 'value2'
];
$response = $client->post('https://example.com/api/endpoint', [
'json' => $body
]);
echo $response->getBody();
In this example, we create a new instance of the Guzzle Client
class. We define an array $body
containing the data we want to send. We then make a POST request to the specified URL, and pass the $body
array as the value of the json
option. Guzzle will automatically serialize the array into JSON and send it in the request.
Note that you need to have Guzzle installed in your project for this code to work. You can install Guzzle using Composer by running composer require guzzlehttp/guzzle
in your project directory.