Skip to content

Instantly share code, notes, and snippets.

@pschultz
Last active December 9, 2021 16:26
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pschultz/6554265 to your computer and use it in GitHub Desktop.
Save pschultz/6554265 to your computer and use it in GitHub Desktop.
Guzzle plugin to force the response charset. Useful ~if~ when webservers lie to you again.
<?php
use Guzzle\Common\Event;
use Guzzle\Http\Message\Header;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ForceCharsetPlugin implements EventSubscriberInterface
{
private $forcedCharset = 'utf8';
public static function getSubscribedEvents()
{
return array(
'request.complete' => 'onRequestComplete'
);
}
public function setForcedCharset($charset)
{
$this->forcedCharset = $charset;
return $this;
}
public function getForcedCharset()
{
return $this->forcedCharset;
}
public function onRequestComplete(Event $event)
{
$response = $event['response'];
$header = $response->getHeader('content-type');
$modified = new Header(
$header->getName(),
array_map(array($this, 'modifyParams'), $header->parseParams()),
$header->getGlue()
);
$response->setHeader('content-type', $modified);
}
private function modifyParams(array $headerParams)
{
$headerParams['charset'] = $this->getForcedCharset();
return urldecode(http_build_query($headerParams, null, ';'));
}
}
<?php
$plugin = new ForceCharsetPlugin();
$plugin->setForcedCharset('utf8');
// Guzzle only
$guzzleClient->addSubscriber($plugin);
// With Goutte
$goutteClient->getClient()->addSubscriber($plugin);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment