5555}
5656$ out ['type ' ] = $ type ;
5757
58- echo json_encode ($ out );
58+ function __json_encode ($ data ) {
59+ if ( is_array ($ data ) || is_object ($ data ) ) {
60+ $ islist = is_array ($ data ) && ( empty ($ data ) || array_keys ($ data ) === range (0 ,count ($ data )-1 ) );
61+
62+ if ( $ islist ) {
63+ $ json = '[ ' . implode (', ' , array_map ('__json_encode ' , $ data ) ) . '] ' ;
64+ } else {
65+ $ items = Array ();
66+ foreach ( $ data as $ key => $ value ) {
67+ $ items [] = __json_encode ("$ key " ) . ': ' . __json_encode ($ value );
68+ }
69+ $ json = '{ ' . implode (', ' , $ items ) . '} ' ;
70+ }
71+ } elseif ( is_string ($ data ) ) {
72+ # Escape non-printable or Non-ASCII characters.
73+ # I also put the \\ character first, as suggested in comments on the 'addcslashes' page.
74+ $ string = '" ' . addcslashes ($ data , "\\\"\n\r\t/ " . chr (8 ) . chr (12 )) . '" ' ;
75+ $ json = '' ;
76+ $ len = strlen ($ string );
77+ # Convert UTF-8 to Hexadecimal Codepoints.
78+ for ( $ i = 0 ; $ i < $ len ; $ i ++ ) {
79+
80+ $ char = $ string [$ i ];
81+ $ c1 = ord ($ char );
82+
83+ # Single byte;
84+ if ( $ c1 <128 ) {
85+ $ json .= ($ c1 > 31 ) ? $ char : sprintf ("\\u%04x " , $ c1 );
86+ continue ;
87+ }
88+
89+ # Double byte
90+ $ c2 = ord ($ string [++$ i ]);
91+ if ( ($ c1 & 32 ) === 0 ) {
92+ $ json .= sprintf ("\\u%04x " , ($ c1 - 192 ) * 64 + $ c2 - 128 );
93+ continue ;
94+ }
95+
96+ # Triple
97+ $ c3 = ord ($ string [++$ i ]);
98+ if ( ($ c1 & 16 ) === 0 ) {
99+ $ json .= sprintf ("\\u%04x " , (($ c1 - 224 ) <<12 ) + (($ c2 - 128 ) << 6 ) + ($ c3 - 128 ));
100+ continue ;
101+ }
102+
103+ # Quadruple
104+ $ c4 = ord ($ string [++$ i ]);
105+ if ( ($ c1 & 8 ) === 0 ) {
106+ $ u = (($ c1 & 15 ) << 2 ) + (($ c2 >>4 ) & 3 ) - 1 ;
107+
108+ $ w1 = (54 <<10 ) + ($ u <<6 ) + (($ c2 & 15 ) << 2 ) + (($ c3 >>4 ) & 3 );
109+ $ w2 = (55 <<10 ) + (($ c3 & 15 )<<6 ) + ($ c4 -128 );
110+ $ json .= sprintf ("\\u%04x \\u%04x " , $ w1 , $ w2 );
111+ }
112+ }
113+ } else {
114+ # int, floats, bools, null
115+ $ json = strtolower (var_export ( $ data , true ));
116+ }
117+ return $ json ;
118+ }
119+
120+ if (function_exists ('json_encode ' )) { // PHP >= 5.2
121+ echo json_encode ($ out );
122+ } else { // PHP < 5.2
123+ echo __json_encode ($ out );
124+ }
59125exit ;
60126?>
0 commit comments