malf stringformat,Laravel中的'格式错误的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.

The following statement

return JsonResponse::create($data);

returns the error below

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());

}

I've changed:

return JsonResponse::create($data);

to

return JsonResponse::create($data, 200, array('Content-Type'=>'application/json; charset=utf-8' ));

but it still isn't working.

How can I fix it?

解决方案

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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值