Last active
August 29, 2019 06:11
-
-
Save jhonata-menezes/382d4ba3e2ab86846bc650adaf8de8bc to your computer and use it in GitHub Desktop.
Guzzle 6: change body response
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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, | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: If there is URL data in
$newBody
, you should replace it withurlencode($newBody)
.https://gist.github.com/jhonata-menezes/382d4ba3e2ab86846bc650adaf8de8bc#file-guzzle_change_body-php-L21