Skip to content

Instantly share code, notes, and snippets.

@jhonata-menezes
Last active August 29, 2019 06:11
Show Gist options
  • Save jhonata-menezes/382d4ba3e2ab86846bc650adaf8de8bc to your computer and use it in GitHub Desktop.
Save jhonata-menezes/382d4ba3e2ab86846bc650adaf8de8bc to your computer and use it in GitHub Desktop.
Guzzle 6: change body response
<?php
/**
* sources:
* http://docs.guzzlephp.org/en/latest/handlers-and-middleware.html#middleware
* https://evertpot.com/222/
*
*/
use GuzzleHttp\Client;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
$handler = HandlerStack::create();
$handler->setHandler(new CurlHandler());
$handler->push(Middleware::mapResponse(function(ResponseInterface $r){
if(isset($r->getHeader('Content-Type')[0]) && $r->getHeader('Content-Type')[0] == 'text/html;charset=ISO-8859-1')
$newBody = utf8_encode(urldecode($r->getBody()->getContents()));
$streamBody = fopen('data://text/plain,' . $newBody,'r');//new resource from string
$newResponse = $r->withoutHeader('Content-Type')
->withHeader('Content-Type', 'text/html; charset=UTF-8')
->withBody(new \GuzzleHttp\Psr7\Stream($streamBody));
return $newResponse;
}
return $r;
}));
$client = new Client([
'handler' => $handler,
]);
@jaceju
Copy link

jaceju commented Aug 29, 2019

Note: If there is URL data in $newBody, you should replace it with urlencode($newBody).

https://gist.github.com/jhonata-menezes/382d4ba3e2ab86846bc650adaf8de8bc#file-guzzle_change_body-php-L21

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment