UTF-8 output with CakePHP

12,354

Solution 1

I had a similar symptom, my solution was to add

'encoding' => 'UTF8' 

to config/database.php

Solution 2

I've had a similar problem to this. Most things are set correctly "out of the box", but I'd just like to point out the following things I found useful... I hit this problem while moving from dev to live:

You need to have matching Database encoding (2 items to check) as well as view encoding.

  • Your DB encoding is set up in the Schema.
  • Cake PHP can be manually forced to expect a type of encoding from the DB.
  • Cake PHP then needs to call the correct encoding for the view as well.

The DB settings are, of course, set up in your database. In my case, using MySQL workbench, this was simply a case of right clicking the schema and selecting "Alter Schema...". From there I could select the encoding/collation I wanted.

In Cake PHP the database encoding is set in app\Config\database.php. You should ensure that the DATABASE_CONFIG array (approx line 60), has the correct encoding enabled/selected. For example:

'encoding' => 'utf8'

Finally, the view needs to select the correct version of HTML to display. This is written into your templates from the file app\Config\core.php (approx line 82).

Configure::write('App.encoding', 'UTF-8');

Once all three parts are changed, you should have a consistent charset and hence display.

Hope that helps any people still searching for this.

Share:
12,354
Benedikt
Author by

Benedikt

Web Developer

Updated on June 12, 2022

Comments

  • Benedikt
    Benedikt almost 2 years

    I'm trying to move some Excel-Data to MySQL, but having troubles with encoding.

    What I did:

    1. Data export from OpenOffice 3.1 as csv (utf-8 encoded)
    2. Import to phpMyAdmin via file upload (Table encoding: 'utf8_unicode_ci')

    In phpMyAdmin's view mode, the data is displayed correctly (it is using utf-8 as charset):

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    

    When I try to display the Data on my webpage, I get a hash with a question mark in it.

    System-Info

    • The language I try to get on my page: German
    • MySQL client version: 5.0.32
    • My OS: MAC OS X 10.5.7
    • Server-Script: CakePHP v1.2.3.8166

    Regards, Benedikt

  • trante
    trante over 11 years
    Don't miss, this line exists in default configuration. But it was commented out.
  • Cullen SUN
    Cullen SUN almost 11 years
    Thanks a lot. you saved me
  • Kevin Cittadini
    Kevin Cittadini over 8 years
    This is the most correct, simpliest and most effective solution that saved my application. Had a full table with ASCII encoding records and this line spared me a lot of utf8_encode() calls
  • Sehdev
    Sehdev over 5 years
    Question is related to Cakphp .
  • developer_chd
    developer_chd over 5 years
    I know @Sehdev , So in some cases when we set 'encoding' => 'utf8' in configuration file it not works. So you can use this.