search
HomeBackend DevelopmentPHP TutorialPHP json_encode analysis_PHP tutorial

PHP json_encode analysis_PHP tutorial

Jul 14, 2016 am 10:08 AM
encodejsonphpspadvantageanalyzelikeexistIuseofoutput

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?
{a : 'abc'}
{'a' : 'abc'}
{a : "abc"}
{"a" : "abc"}
As you all know, only the fourth type is the standard json format.
I do this
$ret_json='{"%s":"%s"}';
echo json_encode($ret_json,"a","abc");
It must also meet the standards.
In this case, I have to ask more deeply, what is the difference between the json format generated by json_encode?
Upload the 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;
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
PHP_JSON_API void php_json_encode(smart_str *buf, zval *val, int options TSRMLS_DC) /* {{{ */
{
switch (Z_TYPE_P(val))
{
case IS_NULL:
                                                                                                                                                                                                to                         ‐ down ‐ ‐ ‐ ‐ ‐ ‐ s ​ ​ ​ smart_str_appendl(buf, "null", 4); // Output NULL
break;
case IS_BOOL:
                                                                                                                                                                                 
Smart_Str_appendl (buf, "true", 4); // Output true
                                                                                  
Smart_Str_appendl (buf, "false", 5); // Output false
                                                                                                 
break;
case IS_LONG:
                                                                                                                                                                                    to                                           out ‐ to ‐ ‐ ‐ ‐ ‐ ​ ​ ​ ​ smart_str_append_long(buf, Z_LVAL_P(val));//Output the value of long integer
break;
case IS_DOUBLE:
                                                                                       
                          char *d = NULL;
int len;
                                double dbl = Z_DVAL_P(val); 
  
                                if (!zend_isinf(dbl) && !zend_isnan(dbl)) {//非无穷尽 
                                        len = spprintf(&d, 0, "%.*k", (int) EG(precision), dbl); 
                                        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; 
很明显,根据不同的类型,会有相应的case。
最复杂的是 字符串 、数组 、对象这三种类型,数组和对象是同一种操作。
先看看字符串吧,很长,注释直接写在代码里。
 
 
 
//options应该是5.3版本之后才支持的,由以下常量组成的二进制掩码: 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.虽然我没用过。。。 
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) {//如果长度为0,则直接返回 双引号 "" 
                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) {  
                                                                                                                                                                                           
                                                                                                                                                                                                                                                                                                    to
                    } else if (type == IS_DOUBLE) {  
                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                      to
                                                                                              int l = spprintf(&tmp, 0, "%.*k", (int) EG(precision), d);
Smart_Str_appendl (buf, tmp, l);
                                                                                                                                                                                 
                                                                                                                     
                                              php_error_docref(NULL TSRMLS_CC, E_WARNING, "double %.9g does not conform to the JSON spec, encoded as 0", d);
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. For example, 1 is 49 and a is 97, and then saved to utf16.
If (len
if (utf16) {
efree(utf16);
        }  
if (len
JSON_G(error_code) = PHP_JSON_ERROR_UTF8;
                                                                                                                                                                                     
                              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
{
us = utf16[pos++];
switch (us)
                                                                         
case '"':
if (options & php_json_hex_quot) {
Smart_Str_appendl (buf, "\ u0022", 6);
                                                                                                                     
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':
                                                                                                                                                                                                                                                                                                    to
break;
case 'n':
                                                  smart_str_appendl(buf, "\n", 2);      
break;
case 'r':
                                                    smart_str_appendl(buf, "\r", 2);        
break;
case 't':
                                                                                                                                                                                                                                                                                                    to
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) { 
                                        smart_str_appendl(buf, "\u0027", 6); 
                                } else { 
                                        smart_str_appendc(buf, '''); 
                                } 
                                break; 
  
                        default: //一直到这里,没有特殊字符就会把值append到buf中 
                                if (us >= ' ' && (us & 127) == us) { 
                                        smart_str_appendc(buf, (unsigned char) us); 
                                } else { 
                                        smart_str_appendl(buf, "\u", 2); 
                                        us = REVERSE16(us); 
  
                                        smart_str_appendc(buf, digits[us & ((1
                                        us >>= 4; 
                                        smart_str_appendc(buf, digits[us & ((1
                                        us >>= 4; 
                                        smart_str_appendc(buf, digits[us & ((1
                                        us >>= 4; 
                                        smart_str_appendc(buf, digits[us & ((1
                                } 
                                break; 
                } 
        } 
        smart_str_appendc(buf, '"'); //结束 双引号。 
        efree(utf16); 
再来看看数组和对象,也很简单,
 
 
 
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] == '
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool