dongyong5255 2015-07-12 21:09
浏览 163
已采纳

laravel 5.1从mysql返回乱码

I am new to laravel framework. I am using Homestead as my development environment and everything works fine. The problem is that I insert Persian language records into mysql database and when I return them in some views, the Persian charecters gets garbled (e.g "آذرشهر" returned as "\u0622\u0630\u0631\u0634\u0647\u0631"). Before using laravel I had a simillar problem which was solved using mysqli_set_charset. my old code was this:

class MySQLDatabase {
      private  $connection;
      public function __construct(){
            $this->openConnection();
            mysqli_set_charset($this->connection, 'utf8');
      }
      public function openConnection(){
            $this->connection=mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);

            if(mysqli_connect_errno()){
                  die("Database connection failed:" .
                        mysqli_connect_error().
                        "(". mysqli_connect_errno().")"
                  );
            }
      }

My laravel database config file is like this:

'default' => env('DB_CONNECTION', 'mysql'),
'mysql' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST', 'localhost'),
            'database'  => env('DB_DATABASE', 'forge'),
            'username'  => env('DB_USERNAME', 'forge'),
            'password'  => env('DB_PASSWORD', ''),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],

and the .env file is like this:

APP_ENV=local
APP_DEBUG=true
APP_KEY=XXXXXXXX

DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

How can I fix this problem?

This is a view:

 @extends('app')

    @section('content')
            <h1>شهر</h1>
            @foreach($cities as $city)
            {{ $city }}
            @endforeach
    @stop

and the resulting object is like this:

{"id":402,"city":"\u0622\u0630\u0631\u0634\u0647\u0631","province_id":1,"created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00"}

  • 写回答

1条回答 默认 最新

  • dsjmrpym220113739 2015-07-13 04:04
    关注

    In fact this has nothing with Laravel. The problem was that I tried to return a whole object (i.e. {{$city}}) to my view while I should return the city name like this: {{$city->city}}

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?