Home >Backend Development >PHP Tutorial >Introduction to the use of json_encode in PHP

Introduction to the use of json_encode in PHP

不言
不言Original
2018-08-03 14:59:442032browse

This article introduces to you the use of json_encode in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Suppose there is such a URL

$url = "https://www.baidu.com?key=你好";$data = ["url" => $url];echo json_encode($data);

Get such an output

{"url":"https:\/\/www.baidu.com?key=\u4f60\u597d"}

First of all, I found that the Chinese became hexadecimal after encoding. This is not garbled code, but a purely practical method. Changed, because you only need to directly deserialize to get the original result, as follows:

//代码$jsonStr = '{"url":"https:\/\/ 
$data = json_decode($jsonStr);
print_r($data);//输出stdClass Object
(
    [url] => https://www.baidu.com?key=你好)

It can be seen that this is not garbled code, so let’s talk about the topic. Although it is not garbled code, looking at the hexadecimal total It affects reading

You can add a parameter injson_encode

//代码
$url = "https://www.baidu.com?key=你好";$data = ["url" => $url];
echo json_encode($data, JSON_UNESCAPED_UNICODE);
//输出
{"url":"https:\/\/www.baidu.com?key=你好"}

I found that Chinese can be displayed normally, but there is another problem that the backslash is automatically escaped. The characters \

look quite uncomfortable. Is there any way to remove the escape character?

//代码
$url = " 
$data = ["url" => $url];
echo json_encode($data, JSON_UNESCAPED_SLASHES);
//输出
{"url":"https://www.baidu.com?key=\u4f60\u597d"}

Now the escape character is removed, but the Chinese character becomes 16 again. System, I want to remove the escape characters and display Chinese normally.

Inspired by *nix-like permission management, I found that I can use the XOR operation

//代码$url = " 
$data = ["url" => $url];
echo json_encode($data, JSON_UNESCAPED_UNICODE ^ JSON_UNESCAPED_SLASHES);
//输出
{"url":"https://www.baidu.com?key=你好"}

to get the job done.

In addition,

Because of the particularity of JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES, because they are all passed 1 < < n (n is an integer) is obtained, so not only can XOR operation be used, but addition can also be used directly

//该等式为true((1<<1) ^ (1<<2)) === ((1<<1) + (1<<2))

Recommended related articles:

PHP Detailed explanation of this part of the namespace

How does php use curl to receive the POST address, that is, how to create an interface

The above is the detailed content of Introduction to the use of json_encode in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn