PHP utf 8 encoding problem utf8 encoding database garbled code page display output garbled code

  • 2020-05-30 19:42:27
  • OfStack

Old long, with this puzzle is a lot of problems, if processes is not good, is garbled, said these words is not I'm very proficient in coding, but in this case is too careful, sum up the 1 bit of little experience, prone to the code of the place have php file, database storage codes, page displays, data transmission) :

1. When building a database, especially when dealing with MYSQL with phpMyAdmin, 1 is usually utf-8, and the field is utf8_general_ci

Database setup:

Find in the my.ini file:
default-character-set = utf8
default-character-set = utf8
init_connect = 'SET NAMES utf8 '
All are set to utf8
Save and restart the mysql service

2. mysql_query("set names 'utf8'") when dealing with data; Note :utf8, not utf-8

3. The default code of PHP is ANSI, which needs to be converted to UTF-8. As for how to convert editplus, there is such a function. UTF-8 + BOM, if you choose this, you will have problems dealing with session, so you must pay attention to 1. Other people develop in eclipse,Myeclipse,ZendStudio, eclipse, ISO-8859-1 is the default in eclipse, which needs to be in the "window" - > Preferences opens the preferences window on the left, general - > "Workspace", in the "text file encoding" set the default encoding to utf-8

4. In the PHP file, you should write: such as < meta http-equiv="Content-Type" Content="text/html;charset=utf-8" >


<?php header('Content-Type:text/html;charset=utf-8');?>  

5. In addition, when dealing with Chinese and other double bytes, there may be scrambled codes. PHP can use iconv,mb_convert_encoding to deal with double bytes, and the rest can refer to PHP help manual

6. In the supplement 1 point (missing 1 point), in your application you need to know data transmission may exist between the coding problem, but you don't know what passed data is to use the code, inside the PHP provides methods to deal with, the following was written by myself a simple way, l can refer to

// Code conversion   
        function display_fileencoding($filename)  
                $code=mb_detect_encoding($filename);// Detect string encoding   
                $filename=mb_convert_encoding($filename,"UTF-8",$code);// The encoding $code convert utf-8 coding   
                return $filename;  
                die(" Please check that the system is installed correctly mbstring");  

Make sure mbstring is enabled in your php.ini

7. Ensure that the above several code 1 to be ok!! Database, web page output will not appear garbled code, if there is wrong, please note out!!

Related articles: