Two example methods for parsing json data using php

Source: Internet
Author: User

Two example methods for parsing json data using php

 

Most popular Web services, such as twitter, provide data through open APIs, always know how to parse various transfer formats of API data, including JSON and XML.


$ Json_string = '{"id": 1, "name": "php100.com", "email": "php tutorial"> admin@php100.com "," interest ": [" wordpress ", "php"]} ';
$ Obj = json_decode ($ json_string );
Echo $ obj-> name; // prints foo
Echo $ obj-> interest [1]; // prints php


Ecshop json parsing class

If (! Defined ('EC _ charset '))
{
Define ('EC _ charset', 'utf-8 ');
}

Class JSON
{
Var $ at = 0;
Var $ ch = '';
Var $ text = '';

Function encode ($ arg, $ force = true)
{
Static $ _ force;
If (is_null ($ _ force ))
{
$ _ Force = $ force;
}

If ($ _ force & EC_CHARSET = 'utf-8' & function_exists ('json _ encoding '))
{
Return json_encode ($ arg );
}

$ ReturnValue = '';
$ C = '';
$ I = '';
$ L = '';
$ S = '';
$ V = '';
$ Numeric = true;

Switch (gettype ($ arg ))
{
Case 'array ':
Foreach ($ arg AS $ I =>$ v)
{
If (! Is_numeric ($ I ))
{
$ Numeric = false;
Break;
}
}

If ($ numeric)
{
Foreach ($ arg AS $ I =>$ v)
{
If (strlen ($ s)> 0)
{
$ S. = ',';
}
$ S. = $ this-> encode ($ arg [$ I]);
}

$ ReturnValue = '['. $ s. ']';
}
Else
{
Foreach ($ arg AS $ I =>$ v)
{
If (strlen ($ s)> 0)
{
$ S. = ',';
}
$ S. = $ this-> encode ($ I). ':'. $ this-> encode ($ arg [$ I]);
}

$ ReturnValue = '{'. $ s .'}';
}
Break;

Case 'object ':
Foreach (get_object_vars ($ arg) AS $ I => $ v)
{
$ V = $ this-> encode ($ v );

If (strlen ($ s)> 0)
{
$ S. = ',';
}
$ S. = $ this-> encode ($ I). ':'. $ v;
}

$ ReturnValue = '{'. $ s .'}';
Break;

Case 'integer ':
Case 'double ':
$ ReturnValue = is_numeric ($ arg )? (String) $ arg: 'null ';
Break;

Case 'string ':
$ ReturnValue = '"'. strtr ($ arg, array (
"R" => 'R', "n" => 'n', "t" => 'T', "B" => 'B ',
"F" => 'F', ''=> '\', '"' => '"',
"X00" => 'u000000', "x01" => 'u0001 ', "x02" => 'u0002', "x03" => 'u0003 ',
"X04" => 'u0004', "x05" => 'u0005 ', "x06" => 'u0006', "x07" => 'u0007 ',
"X08" => 'B', "x0b" => 'u000b', "x0c" => 'F', "x0e" => 'u000e ',
"X0f" => 'u000f', "x10" => 'u0010', "x11" => 'u0011', "x12" => 'u0012 ',
"X13" => 'u0013', "x14" => 'u0014', "x15" => 'u0015', "x16" => 'u0016 ',
"X17" => 'u0017', "x18" => 'u0018', "x19" => 'u0019', "x1a" => 'u001a ',
"X1b" => 'u001b ', "x1c" => 'u001c', "x1d" => 'u001d ', "x1e" => 'u001e ',
"X1f" => 'u001f'
)).'"';
Break;

Case 'boolean ':
$ ReturnValue = $ arg? 'True': 'false ';
Break;

Default:
$ ReturnValue = 'null ';
}

Return $ returnValue;
}

Function decode ($ text, $ type = 0) // The default type = 0 returns obj, type = 1 returns array
{
If (empty ($ text ))
{
Return '';
}
Elseif (! Is_string ($ text ))
{
Return false;
}

If (EC_CHARSET = 'utf-8' & function_exists ('json _ decode '))
{
Return $ this-> addslashes_deep_obj (json_decode (strips tutorial lashes ($ text), $ type ));
}

$ This-> at = 0;
$ This-> ch = '';
$ This-> text = strtr (stripslashes ($ text), array (
"R" => ''," n "=>'', "t" => ''," B "=> '',
"X00" => ''," x01 "=>'', "x02" => ''," x03 "=> '',
"X04" => ''," x05 "=>'', "x06" => ''," x07 "=> '',
"X08" => ''," x0b "=>'', "x0c" => ''," x0e "=> '',
"X0f" => ''," x10 "=>'', "x11" => ''," x12 "=> '',
"X13" => ''," x14 "=>'', "x15" => ''," x16 "=> '',
"X17" => ''," x18 "=>'', "x19" => ''," x1a "=> '',
"X1b" => ''," x1c "=>'', "x1d" => ''," x1e "=> '',
"X1f" =>''
));

$ This-> next ();
$ Return = $ this-> val ();

$ Result = empty ($ type )? $ Return: $ this-> object_to_array ($ return );

Return addslashes_deep_obj ($ result );
}

/**
* Triggers a PHP_ERROR
*
* @ Access private
* @ Param string $ m error message
*
* @ Return void
*/
Function error ($ m)
{
Trigger_error ($ m. 'At offset '. $ this-> at.': '. $ this-> text, E_USER_ERROR );
}

/**
* Returns the next character of a JSON string
*
* @ Access private
*
* @ Return string
*/
Function next ()
{
$ This-> ch =! Isset ($ this-> text {$ this-> })? '': $ This-> text {$ this-> };
$ This-> at ++;

Return $ this-> ch;
}

/**
* Handles strings
*
* @ Access private
*
* @ Return void
*/
Function str ()
{
$ I = '';
$ S = '';
$ T = '';
$ U = '';

If ($ this-> ch = '"')
{
While ($ this-> next ()! = Null)
{
If ($ this-> ch = '"')
{
$ This-> next ();

Return $ s;
}
Elseif ($ this-> ch = '')
{
Switch ($ this-> next ())
{
Case 'B ':
$ S. = 'B ';
Break;

Case 'F ':
$ S. = 'F ';
Break;

Case 'N ':
$ S. = 'n ';
Break;

Case 'r ':
$ S. = 'R ';
Break;

Case 'T ':
$ S. = 'T ';
Break;

Case 'U ':
$ U = 0;

For ($ I = 0; $ I <4; $ I ++)
{
$ T = (integer) sprintf ('% 01c', hexdec ($ this-> next ()));

If (! Is_numeric ($ t ))
{
Break 2;
}
$ U = $ u * 16 + $ t;
}

$ S. = chr ($ u );
Break;
Case ''':
$ S. = ''';
Break;
Default:
$ S. = $ this-> ch;
}
}
Else
{
$ S. = $ this-> ch;
}
}
}

$ This-> error ('bad string ');
}

/**
* Handless arrays
*
* @ Access private
*
* @ Return void
*/
Function arr ()
{
$ A = array ();

If ($ this-> ch = '[')
{
$ This-> next ();

If ($ this-> ch = ']')
{
$ This-> next ();

Return $;
}

While (isset ($ this-> ch ))
{
Array_push ($ a, $ this-> val ());

If ($ this-> ch = ']')
{
$ This-> next ();

Return $;

}
Elseif ($ this-> ch! = ',')
{
Break;
}

$ This-> next ();

}

$ This-> error ('bad array ');
}
}

/**
* Handles objects
*
* @ Access public
*
* @ Return void
*/
Function obj ()
{
$ K = '';
$ O = new StdClass ();

If ($ this-> ch = '{')
{
$ This-> next ();

If ($ this-> ch = '}')
{
$ This-> next ();

Return $ o;
}

While ($ this-> ch)
{
$ K = $ this-> str ();

If ($ this-> ch! = ':')
{
Break;
}

$ This-> next ();
$ O-> $ k = $ this-> val ();

If ($ this-> ch = '}')
{
$ This-> next ();

Return $ o;
}
Elseif ($ this-> ch! = ',')
{
Break;
}

$ This-> next ();
}
}

$ This-> error ('bad object ');
}

/**
* Handles objects
*
* @ Access public
*
* @ Return void
*/
Function assoc ()
{
$ K = '';
$ A = array ();

If ($ this-> ch = '<')
{
$ This-> next ();

If ($ this-> ch = '> ')
{
$ This-> next ();

Return $;
}

While ($ this-> ch)
{
$ K = $ this-> str ();

If ($ this-> ch! = ':')
{
Break;
}

$ This-> next ();
$ A [$ k] = $ this-> val ();

If ($ this-> ch = '> ')
{
$ This-> next ();

Return $;
}
Elseif ($ this-> ch! = ',')
{
Break;
}

$ This-> next ();
}
}

$ This-> error ('bad associative array ');
}

/**
* Handles numbers
*
* @ Access private
*
* @ Return void
*/
Function num ()
{
$ N = '';
$ V = '';

If ($ this-> ch = '-')
{
$ N = '-';
$ This-> next ();
}

While ($ this-> ch> = '0' & $ this-> ch <= '9 ')
{
$ N. = $ this-> ch;
$ This-> next ();
}

If ($ this-> ch = '.')
{
$ N. = '.';

While ($ this-> next () & $ this-> ch> = '0' & $ this-> ch <= '9 ')
{
$ N. = $ this-> ch;
}
}

If ($ this-> ch = 'E' | $ this-> ch = 'E ')
{
$ N. = 'E ';
$ This-> next ();

If ($ this-> ch = '-' | $ this-> ch = '+ ')
{
$ N. = $ this-> ch;
$ This-> next ();
}

While ($ this-> ch> = '0' & $ this-> ch <= '9 ')
{
$ N. = $ this-> ch;
$ This-> next ();
}
}

$ V + = $ n;

If (! Is_numeric ($ v ))
{
$ This-> error ('bad number ');
}
Else
{
Return $ v;
}
}

/**
* Handles words
*
* @ Access private
*
* @ Return mixed
*/
Function word ()
{
Switch ($ this-> ch)
{
Case 'T ':

If ($ this-> next () = 'R' & $ this-> next () = 'U' & $ this-> next () = 'E ')
{
$ This-> next ();

Return true;
}
Break;

Case 'F ':
If ($ this-> next () = 'A' & $ this-> next () = 'l' & $ this-> next () ='s '& $ this-> next () = 'E ')
{
$ This-> next ();

Return false;
}
Break;

Case 'N ':
If ($ this-> next () = 'U' & $ this-> next () = 'l' & $ this-> next () = 'l ')
{
$ This-> next ();

Return null;
}
Break;
}

$ This-> error ('syntax error ');
}

/**
* Generic value handler
*
* @ Access private
*
* @ Return mixed
*/
Function val ()
{
Switch ($ this-> ch)
{
Case '{':
Return $ this-> obj ();

Case '[':
Return $ this-> arr ();

Case '<':
Return $ this-> assoc ();

Case '"':
Return $ this-> str ();

Case '-':
Return $ this-> num ();

Default:
Return ($ this-> ch> = '0' & $ this-> ch <= '9 ')? $ This-> num (): $ this-> word ();
}
}

/**
* Gets the properties of the given object recursion
*
* @ Access private
*
* @ Return array
*/
Function object_to_array ($ obj)
{
$ _ Arr = is_object ($ obj )? Get_object_vars ($ obj): $ obj;
Foreach ($ _ arr as $ key => $ val)
{
$ Val = (is_array ($ val) | is_object ($ val ))? $ This-> object_to_array ($ val): $ val;
$ Arr [$ key] = $ val;
}
Return $ arr;
}

 

/**
* Recursively escape special characters in a variable
*
* @ Access public
* @ Param mix $ value
*
* @ Return mix
*/
Function addslashes_deep ($ value)
{
If (empty ($ value ))
{
Return $ value;
}
Else
{
Return is_array ($ value )? Array_map ('addslashes _ deep ', $ value): addslashes ($ value );
}
}

/**
* Escape object member variables or special characters in Arrays
*
* @ Access public
* @ Param mix $ obj object or Array
* @ Author Xuan Yan
*
* @ Return mix object or Array
*/
Function addslashes_deep_obj ($ obj)
{
If (is_object ($ obj) = true)
{
Foreach ($ obj AS $ key => $ val)
{
$ Obj-> $ key = $ this-> addslashes_deep ($ val );
}
}
Else
{
$ Obj = addslashes_deep ($ obj );
}

Return $ obj;
}

/**
* Remove escape characters from special characters in a variable in recursion Mode
*
* @ Access public
* @ Param mix $ value
*
* @ Return mix
*/
Function stripslashes_deep ($ value)
{
If (empty ($ value ))
{
Return $ value;
}
Else
{
Return is_array ($ value )? Array_map ('stripslashes _ deep ', $ value): stripslashes ($ value );
}
}


/**
* Transcode the parameters passed in JSON.
*
* @ Param string $ str
* @ Return string
*/
Function json_str_iconv ($ str)
{
If (EC_CHARSET! = 'Utf-8 ')
{
If (is_string ($ str ))
{
Return ecs_iconv ('utf-8', EC_CHARSET, $ str );
}
Elseif (is_array ($ str ))
{
Foreach ($ str as $ key => $ value)
{
$ Str [$ key] = json_str_iconv ($ value );
}
Return $ str;
}
Elseif (is_object ($ str ))
{
Foreach ($ str as $ key => $ value)
{
$ Str-> $ key = json_str_iconv ($ value );
}
Return $ str;
}
Else
{
Return $ str;
}
}
Return $ str;
}

}

$ String = '{"email": "cc@126.com", "content": "this is a just a test", "type": "0", "id ": "13", "enabled_captcha": "0", "captcha": "", "rank": "5 "}';
$ Json = new JSON ();

$ Cmt = $ json-> json_str_iconv ($ string); // character Transcoding


$ Cmt = $ json-> decode ($ cmt); // decode

Print_r ($ cmt );


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.