Recently in Web Development Category
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);
}
}
?>

Recent Comments
cnhackTNT on 用正则表达式Look-Ahead做带逃逸的变量替换: 晕,被过滤掉了,再试
cnhackTNT on 用正则表达式Look-Ahead做带逃逸的变量替换: s/(? 这样可以
R.Q. on 个性化SSH登录: 酱紫哦,了了 ---