【问题标题】:Laravel "Malformed UTF-8 characters, possibly incorrectly encoded", how to fix?Laravel“格式错误的 UTF-8 字符,可能编码不正确”,如何解决?
【发布时间】:2017-11-01 14:58:25
【问题描述】:

我尝试在我的用户模型中使用以下方法获得的 json 添加属性返回,但我不断得到 ​​p>

 "message": "Malformed UTF-8 characters, possibly incorrectly encoded",
    "exception": "InvalidArgumentException",
    "file": "/var/www/timetool/vendor/laravel/framework/src/Illuminate/Http/JsonResponse.php",

代码

   /**
     * @return string
     */
    public function getAvatarImageAttribute($value)
    {

        if($this->hasMedia('avatar')) {
             $image = $this->getMedia('avatar');
             $img = \Intervention\Image\ImageManagerStatic::make($image[0]->getPath())->encode('data-url');
         }
         elseif (isset($this->blob->dokument)) {
             $img = 'data:image/jpeg;base64,'. base64_encode($this->blob->document);
         } else {
             $img = '';
         }

         return $img;
    }

在控制器中我有

return \Response::json($users, 200, array('Content-Type' => 'application/json;charset=utf8'), JSON_UNESCAPED_UNICODE);

【问题讨论】:

    标签: json attributes blob response laravel-5.5


    【解决方案1】:

    我认为它与只需要 UTF8 字符的 JSON 有关,并且您的 blob 可能包含无效字符。试试 utf8_encode($img)。 http://at2.php.net/manual/en/function.utf8-encode.php 在您的控制器中返回。 Laravel 会为你构建一个合适的 json 响应。

    【讨论】:

      【解决方案2】:

      将此功能粘贴到文档顶部:

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

      调用上述函数转换内容。它有一个参数,它需要blob图像的值(二进制):

      $img = $this->convert_from_latin1_to_utf8_recursively($this->blob->document)
      

      【讨论】:

        【解决方案3】:

        就我而言,问题在于控制器的编码。解决方法是将其转换为UTF8,并修复了该错误。

        【讨论】:

          猜你喜欢
          • 2019-06-30
          • 2018-05-24
          • 2017-02-17
          • 2018-02-28
          • 2018-09-01
          • 2017-11-27
          • 2019-03-01
          相关资源
          最近更新 更多