今天使用redis的时候报错,但是页面显示一塌糊塌,原因是编码错误。
Predis \ Connection \ ConnectionException (10061)
����Ŀ����������ܾ��������ӡ�
private function createExceptionMessage($message) {
$encoding = mb_detect_encoding($message, array("ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5'));
// 如果字符串的编码格式不为UTF_8就转换编码格式,检测代码,检测到是"EUC-CN"
if ($encoding != 'UTF-8') {
$message = mb_convert_encoding($message, 'UTF-8', $encoding);
}
#结束
$parameters = $this->parameters;
if ($parameters->scheme === 'unix') {
return "$message [$parameters->scheme:$parameters->path]";
}
if (filter_var($parameters->host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
return "$message [$parameters->scheme://[$parameters->host]:$parameters->port]";
}
return "$message [$parameters->scheme://$parameters->host:$parameters->port]";
}
参考:
https://www.jianshu.com/p/67801d24d974
namespace App\Http\Controllers;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function test_guzzle_http_get(){
$client = new Client(); //GuzzleHttp\Client
try {
$response = $client->request('GET', 'https://www.baidu.com/',[
'headers'=> [
'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Language' => 'zh-CN,zh;q=0.9,en;q=0.8,sm;q=0.7',
'Accept-Encoding' => 'gzip'
],
'decode_content' => true,// 解密gzip
'connect_timeout' => 10
]);
// print_r($response);
// 转换成页面使用的编码,默认为UTF-8,否则乱码!
$type = $response->getHeader('content-type');
$parsed = Psr7\parse_header($type);
$original_body = (string)$response->getBody();
$utf8_body = mb_convert_encoding($original_body, 'UTF-8', $parsed[0]['charset'] ?: 'UTF-8');
print_r($utf8_body);
} catch (RequestException $e) {
// 此部分是页面出错时输出,如404
echo Psr7\str($e->getRequest());
if ($e->hasResponse()) {
echo Psr7\str($e->getResponse());
}
}
}
}