Technology, Business, and Doritos

Experiences and help from a wandering techy and entrepreneur

Contact Me

Send any questions you have about food, or programming in PHP, MYSQL, DHTML to tmiskin@gmail.com and I will blog it. And I mean any question.

We all love to see ? or ^A characters in our webpages. This comes usually from smart quotes or fancy apostrophes in Word being pasted into our webpages. By default webpages are rendered in ISO 8859-1 encoding. Over the last year I have learned how to get around about every possible reason for this in PHP and MySQL, so here are the things that you can do in PHP/MYSQL/HTML.

1. These weird characters can be caused by the html document itself not being in UTF-8 encoding. To do this just put this in between your “head” section.

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

Or you can add this into PHP

header("Content-type: text/html; charset=UTF-8");

2. Sometimes the problem can be that your content is taken from MySQL, and by default it takes it out of MySQL in ISO 8859-1. To take it out in UTF-8, just put the following code after you connect to your database.

mysql_query("SET CHARACTER SET utf8");

3. If you are pulling in the text from an external file you need to first make sure that it was saved in Unicode format.  In Windows you have to explicitly put a unicode header into the file, which is usually available by checking a box when saving the file.

4. Finally, if you just want to convert the string into ISO 8859-1, then you need to use either the mb_string library or iconv.  I personally like iconv, but it doesn’t matter very much.  To convert with iconv and replace characters that are not in one that are in the other, the below code works in PHP.  The //TRANSLIT is so it replaces characters.  Usage is iconv(inputEnc,outputEnc,stringToConvert).

iconv("UTF-8", "ISO-8859-1//TRANSLIT", $stringToConvert);

If you are still having problems, just email me and I will look into it.

del.icio.us:Fun with text encoding digg:Fun with text encoding furl:Fun with text encoding

Leave a Reply