PHP code example of iammordaty / guzzle-urlencoded-response-middleware

1. Go to this page and download the library: Download iammordaty/guzzle-urlencoded-response-middleware library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

iammordaty / guzzle-urlencoded-response-middleware example snippets


use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use GuzzleUrlEncodedResponseMiddleware\UrlEncodedResponseMiddleware;
use function GuzzleHttp\Psr7\stream_for;

$body = 'id=78349&name=John%20Smith&username=%40smith&email=hello%40smith.com&phone=%2B1-202-555-0192&website=smith.dev';

// IRL: fetch data from server
$mock = new MockHandler([
    (new Response())->withBody(stream_for($body))
]);

$stack = HandlerStack::create($mock);
$stack->push(new UrlEncodedResponseMiddleware(), UrlEncodedResponseMiddleware::NAME);

$client = new Client([ 'handler' => $stack ]);

$response = $client->get('/');
$contents = $response->getBody()->getUrlDecodedParsedContents();

print_r($contents);

/*
Outputs:

Array
(
    [id] => 78349
    [name] => John Smith
    [username] => @smith
    [email] => [email protected]
    [phone] => +1-202-555-0192
    [website] => smith.dev
)
*/

$response->getBody()->rewind();

echo $response->getBody()->getUrlDecodedContents();

// Outputs: id=78349&name=John Smith&username=@smith&[email protected]&phone=+1-202-555-0192&website=smith.dev