Home Backend Development PHP Tutorial PHP json_encode usage analysis instructions_PHP tutorial

PHP json_encode usage analysis instructions_PHP tutorial

Jul 13, 2016 pm 05:07 PM
encode json php introduce use analyze article of illustrate

This article will introduce you to the usage analysis of json_encode. Friends who are interested in understanding the php source code can try to refer to it.

I won’t talk about the advantages of json,

I have a habit, when I output json, I like to use sprintf to spell it into json format,

Two days ago, I was told by a friend that it was not standard and that json_encode must be used to generate the standard json format. Of course I was very depressed,

After using it for so many years, I just realized that this is not standard. Since I say it is not standard, then is the above the standard json format?

The code is as follows Copy code
 代码如下 复制代码

{a : 'abc'} {'a' : 'abc'} {a : "abc"} {"a" : "abc"}

{a : 'abc'} {'a' : 'abc'} {a : "abc"} {"a" : "abc"}


Everyone knows that only the fourth type is the standard json format.

I do this
 代码如下 复制代码

$ret_json='{"%s":"%s"}';

echo json_encode($ret_json,"a","abc");

The code is as follows Copy code

$ret_json='{"%s":"%s"}';

echo json_encode($ret_json,"a","abc");

It must also meet the standards.
 代码如下 复制代码
static PHP_FUNCTION(json_encode)
{
        zval *parameter;
        smart_str buf = {0};
        long options = 0;
 
        if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|l", ¶meter, &options) == FAILURE) {
                return;
        } 
 
        JSON_G(error_code) = PHP_JSON_ERROR_NONE;
 
        php_json_encode(&buf, parameter, options TSRMLS_CC);
 
        ZVAL_STRINGL(return_value, buf.c, buf.len, 1);
 
        smart_str_free(&buf);
}
In this case, I have to ask more deeply, what is the difference between the json format generated by json_encode? Up code
The code is as follows Copy code
static PHP_FUNCTION(json_encode) {          zval *parameter;           smart_str buf = {0}; long options = 0; If (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|l", ¶meter, &options) == FAILURE) {                   return;                                                                                                               ​​​​JSON_G(error_code) = PHP_JSON_ERROR_NONE; ​​​​ php_json_encode(&buf, parameter, options TSRMLS_CC); ​​​ZVAL_STRINGL(return_value, buf.c, buf.len, 1);           smart_str_free(&buf); }

JSON_G(error_code) = PHP_JSON_ERROR_NONE;
It is a defined json error. This error can be obtained through the json_last_error function. Have you used it? I haven't used it anyway.
php_json_encode is the main operation

The code is as follows Copy code

PHP_JSON_API void php_json_encode(smart_str *buf, zval *val, int options TSRMLS_DC) /* {{{ */
{
          switch (Z_TYPE_P(val))
           {
case IS_NULL:
Smart_Str_appendl (buf, "null", 4); // Output null
                          break;

case IS_BOOL:
If (Z_BVAL_P(val)) {
Smart_Str_appendl (buf, "true", 4); // Output true
                             } else {
                                                                                                                                                                                                                                                      out out out out out out out of false
                                                                                                          }                           break;

case IS_LONG:
Smart_Str_append_long (buf, z_lval_p (val)); // Output the value of long plastic surgery
                          break;

case IS_DOUBLE:
                                                                                                                                                                                                                                                                                                                                                              char *d = NULL;
int len;
                                                                                                                                                                                                                                     double dbl = Z_DVAL_P(val);

If (!zend_isinf(dbl) && !zend_isnan(dbl)) {//Not infinite
                                                                                                                                                                                                                                                      len = spprintf(&d, 0, "%.*k", (int) EG(precision), dbl);
                                                                                                                                                                                                                                                    through smart_str_appendl (buf, d, len);
efree(d);
                                } else {
                                        php_error_docref(NULL TSRMLS_CC, E_WARNING, "double %.9g does not conform to the JSON spec, encoded as 0", dbl);
                                        smart_str_appendc(buf, '0');
                                }
                       }
                        break;
 
                case IS_STRING://字符串
                        json_escape_string(buf, Z_STRVAL_P(val), Z_STRLEN_P(val), options TSRMLS_CC);
                        break;
 
                case IS_ARRAY://数组和对象
                case IS_OBJECT:
                        json_encode_array(buf, &val, options TSRMLS_CC);
                        break;
 
                default:
                        php_error_docref(NULL TSRMLS_CC, E_WARNING, "type is unsupported, encoded as null");
                        smart_str_appendl(buf, "null", 4);
                        break;
        }
 
        return;
}

Obviously, there will be corresponding cases according to different types.
The most complex types are string, array, and object. Arrays and objects are the same operation.
Let’s take a look at the string first. It’s very long and the comments are written directly in the code.

The code is as follows Copy code
/options should be supported only after version 5.3, and are binary masks composed of the following constants: JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_UNESCAPED_UNICODE. Although I haven't used it. . .
static void json_escape_string(smart_str *buf, char *s, int len, int options TSRMLS_DC) /* {{{ */
{
int pos = 0;
          unsigned short us;
          unsigned short *utf16;

If (len == 0) {//If the length is 0, return double quotes directly ""
                      smart_str_appendl(buf, """", 2);
                   return;
}

If (options & PHP_JSON_NUMERIC_CHECK) {//Check whether it is a number from 0 to 9, if it is a number, the data will be returned directly as a long or double type.
                       double d;
                 int type;
                     long p;

If ((type = is_numeric_string(s, len, &p, &d, 0)) != 0) {
If (type == IS_LONG) {
                                                                                                                                                                                                                                                             smart_str_append_long(buf, p);
} Else if (type == is_double) {
If (!zend_isinf(d) && !zend_isnan(d)) {
                                                                                               int l = spprintf(&tmp, 0, "%.*k", (int) EG(precision), d);
                                                                                                                                                                                                                                smart_str_appendl (buf, tmp, l);
efree(tmp);
                                                                                                                                                                                                                                                                                     Php_error_docref (null TSRMLS_CC, E_WARNINING, "Double %.9g Does Not Conform to the Json Spec, Encoded as 0", d);
                                                                                                                                                                                                                                                     through smart_str_appendc(buf, '0');
                                                                                                                           }                                                                                                                                                return;
                }

}

​​​​ utf16 = (unsigned short *) safe_emalloc(len, sizeof(unsigned short), 0);
​​​​​ len = utf8_to_utf16(utf16, s, len); //The value you input will be processed once and converted into the corresponding Dec code, such as 1 is 49, a is 97, and saved in utf16.
If (len <= 0) {//If len is less than 0, an error occurs. If you use json_encode to process GBK encoding, it will hang up here.
If (utf16) {
                               efree(utf16);
                }
If (len < 0) {
JSON_G(error_code) = PHP_JSON_ERROR_UTF8;
If (!PG(display_errors)) {
                                                    php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid UTF-8 sequence in argument");
                                                                                                          }                                                                                                                                                                                                                                       smart_str_appendl(buf, "null", 4);
                     } else {
                                                                                                                                                                                                                                      smart_str_appendl(buf, """", 2);
                }
                   return;
}

         smart_str_appendc(buf, '"'); //Input "

//The following code is to escape some special characters such as double quotes, backslashes, etc.
           while (pos < len)
            {
                    us = utf16[pos++];

switch (us)
                                                  {
case '"':
If (options & PHP_JSON_HEX_QUOT) {
                                                                                                                                                                                                                          to                                                                                                                                                                                                                                                                                                                             smart_str_appendl(buf, """, 2);
                                }
                                break;
 
                        case '':
                                smart_str_appendl(buf, "\", 2);
                                break;
case '/':
                                smart_str_appendl(buf, "/", 2);
                                break;
 
                        case 'b':
                                smart_str_appendl(buf, "b", 2);
                                break;
 
                        case 'f':
                                smart_str_appendl(buf, "f", 2);
                                break;
 
                        case 'n':
                                smart_str_appendl(buf, "n", 2);
                                break;
 
                        case 'r':
                                smart_str_appendl(buf, "r", 2);
                                break;
 
                        case 't':
                                smart_str_appendl(buf, "t", 2);
                                break;
 
                        case '<':
                                if (options & PHP_JSON_HEX_TAG) {
                                        smart_str_appendl(buf, "u003C", 6);
                                } else {
                                        smart_str_appendc(buf, '<');
                                }
                                break;
 
                        case '>':
                                if (options & PHP_JSON_HEX_TAG) {
                                        smart_str_appendl(buf, "u003E", 6);
                                } else {
                                        smart_str_appendc(buf, '>');
}
                                break;
 
                        case '&':
                                if (options & PHP_JSON_HEX_AMP) {
                                        smart_str_appendl(buf, "u0026", 6);
                                } else {
                                        smart_str_appendc(buf, '&');
                                }
                                break;
 
                        case ''':
                                if (options & PHP_JSON_HEX_APOS) {
                                                                                                                                                                                                                          to                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         smart_str_appendc(buf, ''');
                                                                                                                           } break;

default: //Up to here, if there are no special characters, the value will be appended to buf
If (us >= ' ' && (us & 127) == us) {
                                                                                                                                                                                                                                                                smart_str_appendc(buf, (unsigned char) us);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 because
Smart_Str_appendc (buf, digits [us & ((1 & lt; & lt; 4) - 1)];
                                                                                                                                                 through Smart_Str_appendc (buf, digits [us & ((1 & lt; & lt; 4) - 1)];
                                                                                                                                                 through Smart_Str_appendc (buf, digits [us & ((1 & lt; & lt; 4) - 1)];
                                                                                                                                                 through Smart_Str_appendc (buf, digits [us & ((1 & lt; & lt; 4) - 1)];
                                                                                                                                                                                                                                                                       break;
                }
}
          smart_str_appendc(buf, '"'); //End double quotes.
        efree(utf16);
}

Let’s look at arrays and objects, they are also very simple,

 代码如下 复制代码
static void json_encode_array(smart_str *buf, zval **val, int options TSRMLS_DC) /* {{{ */
{
        int i, r;
        HashTable *myht;
 
        if (Z_TYPE_PP(val) == IS_ARRAY) {
                myht = HASH_OF(*val);
                r = (options & PHP_JSON_FORCE_OBJECT) ? PHP_JSON_OUTPUT_OBJECT : json_determine_array_type(val TSRMLS_CC);
        } else {
                myht = Z_OBJPROP_PP(val);
                r = PHP_JSON_OUTPUT_OBJECT;
        } 
 
        if (myht && myht->nApplyCount > 1) {
                php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected");
                smart_str_appendl(buf, "null", 4);
                return;
        }
//开始标签
        if (r == PHP_JSON_OUTPUT_ARRAY) {
                smart_str_appendc(buf, '[');
        } else {
                smart_str_appendc(buf, '{');
        } 
 
        i = myht ? zend_hash_num_elements(myht) : 0;
 
        if (i > 0)
        {
                char *key;
                zval **data;
                ulong index;
                uint key_len;
                HashPosition pos;
                HashTable *tmp_ht;
                int need_comma = 0;
 
                zend_hash_internal_pointer_reset_ex(myht, &pos);
//便利哈希表
                for (;; zend_hash_move_forward_ex(myht, &pos)) {
                        i = zend_hash_get_current_key_ex(myht, &key, &key_len, &index, 0, &pos);
                        if (i == HASH_KEY_NON_EXISTANT)
                                break;
 
                        if (zend_hash_get_current_data_ex(myht, (void **) &data, &pos) == SUCCESS) {
                                tmp_ht = HASH_OF(*data);
                                if (tmp_ht) {
                                        tmp_ht->nApplyCount++;
                                }
 
                                if (r == PHP_JSON_OUTPUT_ARRAY) {
                                        if (need_comma) {
                                                smart_str_appendc(buf, ',');
                                        } else {
                                                need_comma = 1;
                                        }
//将值append到 buf中
                                        php_json_encode(buf, *data, options TSRMLS_CC);
                                } else if (r == PHP_JSON_OUTPUT_OBJECT) {
                                        if (i == HASH_KEY_IS_STRING) {
                                                if (key[0] == '' && Z_TYPE_PP(val) == IS_OBJECT) {
                                                        /* Skip protected and private members. */
                                                        if (tmp_ht) {
                                                                tmp_ht->nApplyCount--;
                                                        }
                                                        continue;
                                                }
 
                                                if (need_comma) {
                                                        smart_str_appendc(buf, ',');
                                                } else {
                                                        need_comma = 1;
                                                }
 
                                                json_escape_string(buf, key, key_len - 1, options & ~PHP_JSON_NUMERIC_CHECK TSRMLS_CC);
                                                smart_str_appendc(buf, ':');
 
                                                php_json_encode(buf, *data, options TSRMLS_CC);
                                        } else {
                                                if (need_comma) {
                                                        smart_str_appendc(buf, ',');
                                                } else {
                                                        need_comma = 1;
                                                }
 
                                                smart_str_appendc(buf, '"');
                                                smart_str_append_long(buf, (long) index);
                                                smart_str_appendc(buf, '"');
                                                smart_str_appendc(buf, ':');
 
                                                php_json_encode(buf, *data, options TSRMLS_CC);
                                        }
                                }
 
                                if (tmp_ht) {
                                        tmp_ht->nApplyCount--;
                                }
                        }
                }
        }
//结束标签
        if (r == PHP_JSON_OUTPUT_ARRAY) {
                smart_str_appendc(buf, ']');
        } else {
                smart_str_appendc(buf, '}');
        }
}

通过简单分析,证明了一个问题,跟我上面用sprintf的方法其实是一样的,都是拼接字符串,

而且 为了性能,更应该鼓励用sprintf来拼接json格式,

因为 json_encode会进行很多 循环操作,而且所消耗的性能是线性的 O(n^2)。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/629905.htmlTechArticle本文章来给大家介绍json_encode使用分析,兴趣了解php源码的朋友可尝试参考哦。 json的优点就不说了, 有个习惯,我在输出json的时候,喜欢...
Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles