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 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程