php object to JSON

| No Comments | No TrackBacks

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

 $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);
    }
}
?>

No TrackBacks

TrackBack URL: http://mtblog.jianingy.com/mt-tb.cgi/205

Leave a comment

October 2008

Sun Mon Tue Wed Thu Fri Sat
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31  

Friends' Links

Archives

Powered by Movable Type 4.21-en