Tips to solve the garbled Chinese parameters of URL in PHP
With the development of the Internet, Chinese websites are becoming more and more popular, and users also hope to access the website through Chinese parameters. . However, in PHP development, garbled characters often occur when processing URL Chinese parameters, which brings a lot of trouble to developers. This article will introduce several techniques to solve the problem of garbled Chinese URL parameters in PHP, and provide specific code examples.
1. Use urlencode and urldecode
When processing URL Chinese parameters, we can use the urlencode and urldecode functions provided by PHP to encode and decode parameters. The urlencode function is used to convert a string into an encoding format that conforms to the URL specification, while the urldecode function is used to decode the encoded string into the original string.
The sample code is as follows:
$url = 'http://www.example.com/?name=' . urlencode('中文参数'); echo $url; // 输出结果为:http://www.example.com/?name=%E4%B8%AD%E6%96%87%E5%8F%82%E6%95%B0 $name = urldecode($_GET['name']); echo $name; // 输出结果为:中文参数
2. Use mb_convert_encoding
Another way to deal with garbled Chinese parameters in URLs is to use the mb_convert_encoding function for encoding conversion. By specifying the encoding format and target encoding format of the original string, the problem of garbled Chinese parameters can be effectively dealt with.
The sample code is as follows:
$raw = '中文参数'; $encoded = mb_convert_encoding($raw, 'UTF-8', 'GBK'); echo $encoded; // 输出结果为:涓枃鍙傛暟 $decoded = mb_convert_encoding($encoded, 'GBK', 'UTF-8'); echo $decoded; // 输出结果为:中文参数
3. Use htaccess configuration file
In addition to processing garbled Chinese parameters in PHP code, we can also solve it through Apache's htaccess configuration file The problem. By setting RewriteRule rules, the server can correctly handle Chinese parameters in the URL.
The sample code is as follows:
RewriteEngine On RewriteRule ^([^/]*)$ index.php?name= [L]
The above are three techniques to solve the problem of garbled Chinese parameters in URLs in PHP. Developers can choose the appropriate method to deal with garbled Chinese parameters according to their own needs. I hope the content of this article will be helpful to everyone.
The above is the detailed content of Tips to solve the garbled Chinese parameters of URL in PHP. For more information, please follow other related articles on the PHP Chinese website!