Guest User

Untitled

a guest
Dec 7th, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.38 KB | None | 0 0
  1. function json_encode( $data ) {            
  2.      if( is_array($data) || is_object($data) ) {
  3.          $islist = is_array($data) && ( empty($data) || array_keys($data) === range(0,count($data)-1) );
  4.          
  5.          if( $islist ) {
  6.              $json = '[' . implode(',', array_map('__json_encode', $data) ) . ']';
  7.          } else {
  8.              $items = Array();
  9.              foreach( $data as $key => $value ) {
  10.                  $items[] = __json_encode("$key") . ':' . __json_encode($value);
  11.              }
  12.              $json = '{' . implode(',', $items) . '}';
  13.          }
  14.      } elseif( is_string($data) ) {
  15.          # Escape non-printable or Non-ASCII characters.
  16.         # I also put the \\ character first, as suggested in comments on the 'addclashes' page.
  17.         $string = '"' . addcslashes($data, "\\\"\n\r\t/" . chr(8) . chr(12)) . '"';
  18.          $json    = '';
  19.          $len    = strlen($string);
  20.          # Convert UTF-8 to Hexadecimal Codepoints.
  21.         for( $i = 0; $i < $len; $i++ ) {
  22.              
  23.              $char = $string[$i];
  24.              $c1 = ord($char);
  25.              
  26.              # Single byte;
  27.             if( $c1 <128 ) {
  28.                  $json .= ($c1 > 31) ? $char : sprintf("\\u%04x", $c1);
  29.                  continue;
  30.              }
  31.              
  32.              # Double byte
  33.             $c2 = ord($string[++$i]);
  34.              if ( ($c1 & 32) === 0 ) {
  35.                  $json .= sprintf("\\u%04x", ($c1 - 192) * 64 + $c2 - 128);
  36.                  continue;
  37.              }
  38.              
  39.              # Triple
  40.             $c3 = ord($string[++$i]);
  41.              if( ($c1 & 16) === 0 ) {
  42.                  $json .= sprintf("\\u%04x", (($c1 - 224) <<12) + (($c2 - 128) << 6) + ($c3 - 128));
  43.                  continue;
  44.              }
  45.                  
  46.              # Quadruple
  47.             $c4 = ord($string[++$i]);
  48.              if( ($c1 & 8 ) === 0 ) {
  49.                  $u = (($c1 & 15) << 2) + (($c2>>4) & 3) - 1;
  50.              
  51.                  $w1 = (54<<10) + ($u<<6) + (($c2 & 15) << 2) + (($c3>>4) & 3);
  52.                  $w2 = (55<<10) + (($c3 & 15)<<6) + ($c4-128);
  53.                  $json .= sprintf("\\u%04x\\u%04x", $w1, $w2);
  54.              }
  55.          }
  56.      } else {
  57.          # int, floats, bools, null
  58.         $json = strtolower(var_export( $data, true ));
  59.      }
  60.      return $json;
  61.  }
Add Comment
Please, Sign In to add comment