php get request Chinese garbled solution: 1. Use [$name = iconv("gbk","utf-8",$name);] method to solve the garbled code; 2. Use [mb_convert_encoding($ name, "utf-8", "gbk");] method.
Recommended: "PHP Video Tutorial"
php receives garbled Chinese parameters passed in by the GET method
I recently wrote a simple page and passed in Chinese parameters from the browser (test.php?name=test). No matter how I set the utf-8 page, garbled characters were displayed. I googled it. I found a lot of solutions, but what is the cause of the problem? No one has studied this issue in depth. Out of curiosity, I had to check out what was causing it, and it would also gain me some experience!
First, let’s take a look at the simple test code:
<?php header("Content-Type:text/html;charset=UTF-8"); $name = $_GET['name']; var_dump($name); ?>
The test results are as follows:
The code states that the encoding of the response content is utf-8, and the displayed content is indeed garbled. Please note here that the length of the variable output by var_dump is only 4. Obviously, the length of the two Chinese characters must be more than 4 bytes under utf-8 encoding. Then let's take a look at the url of Firefox to access this page
##FireFox will automatically Chinese url encoding, so we can see that the test becomes ����. Obviously, one word here is two bytes, which is Chinese encoding format such as gb2313, gbk, etc., not utf-8 encoding. If we switch the encoding of the page to gbk, the Chinese parameters will display normally, see the picture below
Next we do another test, the code is as follows:
<?php header("Content-Type:text/html;charset=UTF-8"); $name = $_GET['name']; var_dump($name); ?>
$name = iconv("gbk","utf-8",$name);
mb_convert_encoding($name, "utf-8", "gbk");
The above is the detailed content of What should I do if Chinese garbled characters appear in the php get request?. For more information, please follow other related articles on the PHP Chinese website!