Discuss the solution of PHP JSON Chinese gibber in detail

  • 2020-06-07 04:20:14
  • OfStack

We know when using Ajax technology and PHP backstage interaction, the code is often the case in Chinese JSON as a data exchange format, similar to that of the XML when PHP used to interact will also appear in the text garbled, solve PHP JSON garbled method of thinking in Chinese and actually PHP Ajax by value solution similar Chinese characters garbled, I described in detail in the form of tutorials below solve PHP JSON Chinese garbled.

Why does PHP interact with JSON in Chinese?

As JSON is similar to JS1, characters on the client side are processed in the form of UTF8, that is, characters submitted or returned by JSON are processed in the form of UTF8. When interacting with PHP, if database encoding and PHP page encoding are not in the form of UTF8, scrambled characters will be generated when interacting with PHP and JSON.

The method to solve PHP JSON Chinese garbled code

After we know the reason why the interaction between PHP and JSON produces Chinese scrambled code, the solution is actually much simpler.

Solution PHP JSON Chinese disorderly code method 1: ensure the database, front and background PHP page code 1 to send

The simplest solution to PHP JSON Chinese confusing code method is to ensure that the database encoding, PHP page encoding system 1 use UTF8 format, for PHP beginners to build the database had better use UTF8 format, can reduce a lot of trouble.

Method 2: Configure PHP function urlencode and JS function decodeURI()

When PHP USES JSON to interact with foreground JS, it needs to use urlencode function to encode URL before using json_encode function, and read Chinese information after decoding URL via JS function decodeURI() on JS client.

Note: When interacting with JSON on an PHP page, such as converting an array to JSON format, first encode the arrays key and value using the urlencode function and then the json_encode and urldecode functions.

PHP JSON 3: Use string encoding conversion function

When the database encoding and PHP page encoding are not 1 due to various reasons, such as the existing database encoding USES GB2312, then when using JSON interaction, the string encoding conversion function is needed for the conversion between character sets. Common functions are iconv. Since iconv requires PHP configuration environment support, if not, you can achieve the encoding conversion by writing gbk and UTF8 encoding conversion functions by yourself.

At this point, three solutions of PHP JSON Chinese character scrambled code are introduced. In fact, in the development of PHP, PHP and AJAX/JS interact with each other, and these methods are basically used when generating Chinese scrambled code, with similar ideas.

Related articles: