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:

* Info:
function ob_utf8($string) {
	return utf8_decode($string);

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:

$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: , , ,