#39;Malformed UTF-8 characters, possibly incorrectly encoded#39; in Laravel(Laravel 中的“格式错误的 UTF-8 字符,可能编码不正确)
本文介绍了Laravel 中的“格式错误的 UTF-8 字符,可能编码不正确"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 Laravel(一个 PHP 框架)为移动设备编写服务,并以 JSON
格式返回数据.在数据结果中有一些字段以UTF-8
编码.
I'm using Laravel (a PHP framework) to write a service for mobile and have the data returned in JSON
format. In the data result there are some fields encoded in UTF-8
.
以下声明
return JsonResponse::create($data);
返回以下错误
InvalidArgumentException
HELP
Malformed UTF-8 characters, possibly incorrectly encoded
Open: /var/www/html/vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/JsonResponse.php
} catch (Exception $exception) {
restore_error_handler();
throw $exception;
}
if (JSON_ERROR_NONE !== json_last_error()) {
throw new InvalidArgumentException($this->transformJsonError());
}
我变了:
return JsonResponse::create($data);
到
return JsonResponse::create($data, 200, array('Content-Type'=>'application/json; charset=utf-8' ));
但它仍然无法正常工作.
but it still isn't working.
我该如何解决?
推荐答案
我编写了这个方法来处理 UTF8 数组和 JSON 问题.它适用于数组(简单和多维).
I wrote this method to handle UTF8 arrays and JSON problems. It works fine with array (simple and multidimensional).
/**
* Encode array from latin1 to utf8 recursively
* @param $dat
* @return array|string
*/
public static function convert_from_latin1_to_utf8_recursively($dat)
{
if (is_string($dat)) {
return utf8_encode($dat);
} elseif (is_array($dat)) {
$ret = [];
foreach ($dat as $i => $d) $ret[ $i ] = self::convert_from_latin1_to_utf8_recursively($d);
return $ret;
} elseif (is_object($dat)) {
foreach ($dat as $i => $d) $dat->$i = self::convert_from_latin1_to_utf8_recursively($d);
return $dat;
} else {
return $dat;
}
}
// Sample use
// Just pass your array or string and the UTF8 encode will be fixed
$data = convert_from_latin1_to_utf8_recursively($data);
这篇关于Laravel 中的“格式错误的 UTF-8 字符,可能编码不正确"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:Laravel 中的“格式错误的 UTF-8 字符,可能编码不正确"


猜你喜欢
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01