Recently in Web Development Category

php object to JSON

| | Comments (0) | TrackBacks (0)

PHP默认的那个extension在转换json的时候会把UTF-8字符用"\xxx"方式表示出来,因此十分浪费带宽。所以自己又写了一个出来。

<?php
abstract class Jsonable
{
 
     public function toJSON($quote = false) 
     {
          return self::_objectToJSON($this, $quote);
      }
 
     protected function _objectToJSON($obj, $quote) 
     {
          $ppt = get_object_vars($this);
          $aj = array();
  
          foreach ($ppt as $key => $val) {
               if (is_array($val)) {
                    array_push($aj, self::_arrayTOJSON($val, $quote));
                } else if (is_object($val)) {
                    array_push($aj, self::_objectTOJSON($val, $quote));
                } else {
                    if ($quote)
                        $key = '"'.self::_escape($key).'"'; 
                    else
                        $key = self::_escape($key);
                    if (!is_numeric($val) || $quote)
                        $val = '"'.self::_escape($val).'"';
                    array_push($aj, $key.':'.$val);
                }
           }
          if ($quote)
              $key = '"'.self::_escape(get_class($obj)).'"'; 
          else
              $key = self::_escape(get_class($obj));
  
          return $key.':{'.join(',', $aj).'}';
      }
 
     protected function _arrayToJSON($arr, $quote) 
     {
          $aj = array();
          foreach( $arr as $item) {
               if (is_array($item)) {
                    array_push($aj, self::_arrayToJSON($item, $quote));
                } else if (is_object($item)) {
                    array_push($aj, self::_objectToJSON($item, $quote));
                } else {
                    if (!is_numeric($item) || $quote)
                        $item = '"'.self::_escape($item).'"';
                    array_push($aj, $item);
                }
           }
  
          return '['.join(',', $aj).']';
      }
     private function _escape($s) 
     {
          $boys = array('\\', '"', "\r", "\n","'","/");
          $girls = array('\\\\', '\"', '\x0D', '\x0A',"\'","\/");
          return str_replace($boys, $girls, $s);
      }
}

class JSONUtil extends Jsonable{
     public function arrayToJSON($arr, $quote = false) 
     {
          return self::_arrayToJSON($arr, $quote);
      }
}
?>
声援SOFF|声援珊瑚虫:如果你是珊瑚虫用户,请坚决力挺声援珊瑚虫!

Recent Posts

Archives