Archive

Posts Tagged ‘UTF8’

Talking in tongues – UTF8 with CodeIgniter

February 16th, 2009 14 comments

PHP 4 & 5 unfortunately have major problems working with UTF8. Hopefully this will be solved with PHP6 and its fancy pants new rendering interface.

Until then we have to make do and mend.

First setup your database to work with UTF8. I won’t waste time telling you how to do this in MySQL as many people far brighter than I have written more on the subject.

CodeIgniter comes with UTF8 enabled out of the box so there is little to do configuration wise. Unfortunately pasting a test string such as: 検索 (which I stole from this Wikipedia page) into a CI input box will quickly lead to calamity as CI tries to save the string as ASCII.

Simple solution then, save the following helper in your system/application/helpers folder:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Rewrite all outgoing text into UTF8 compatible streams
* Author: Matt Carter <m@ttcarter.com>
* Info: http://hashbang.net/2009/02/utf8-with-codeigniter
*/
function ob_utf8($string) {
	return utf8_decode($string);
}
ob_start('ob_utf8');
 
foreach ($_POST as $key => $val) // Re-write all incoming text into UTF8 streams
	$_POST[$key] = utf8_encode($val);
?>

Then simply add it to your system/application/autoload.php:

1
$autoload['helper'] = array('utf8');

The helper will automatically convert incoming POST data into MySQL compatible UTF8 and convert outgoing text into HTML UTF8 streams.

Categories: PHP Tags: , , ,