本文介紹了Laravel 中的“格式錯誤的 UTF-8 字符,可能編碼不正確"的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我正在使用 Laravel(一個 PHP 框架)為移動設(shè)備編寫服務(wù),并以 JSON
格式返回數(shù)據(jù).在數(shù)據(jù)結(jié)果中有一些字段以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 數(shù)組和 JSON 問題.它適用于數(shù)組(簡單和多維).
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);
這篇關(guān)于Laravel 中的“格式錯誤的 UTF-8 字符,可能編碼不正確"的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!