///////////////////////////////////////////////////////////////////////
// Serializer - class for serializer of php objects/arrays/primitives
// into different data formats.
//
// Useful for Ajax, php-to-php or java-to-php webservices.
//
// Copyright (C) 2007 Yanik Gleyzer
//
// License: LGPL
///////////////////////////////////////////////////////////////////////
/**
* Serializer
* @author Yanik Gleyzer
* @copyright 2007 Yanik Gleyzer
*/
class Serializer{
/**
* Main static function.
* Returns serialized string according to format
* @param mixed $obj
* @param string $format
* @throws exception if formt not supported
* @return string
*/
function serialize($obj,$format='php'){
if($format == '') $format = 'php';
$o = new Serializer();
$method = $format.'_serialize';
if(method_exists($o,$method))
return $o->$method($obj);
throw new Exception('Format "'.$format.'" not supported');
}
/**
* Php serialization
* @param mixed $o
* @return string
*/
function php_serialize($o){
return serialize($o);
}
/**
* Javascript serialization
* @param mixed $o
* @return string
*/
function js_serialize($o){
if(is_array($o)){
$arr = array();
$symbolic = false;
foreach($o as $k=>$s){
if(!is_numeric($k)){
$symbolic = true;
break;
}
}
if($symbolic){
foreach($o as $k=>$s){
$arr[] = $this->js_serialize($k).':'.$this->js_serialize($s);
}
return '{'.implode(',',$arr).'}';
}
else{
foreach($o as $s){
$arr[] = $this->js_serialize($s);
}
return '['.implode(',',$arr).']';
}
}
else if(is_object($o)){
$arr = array();
foreach(get_object_vars($o) as $k=>$s){
$arr[] = $this->js_serialize($k).':'.$this->js_serialize($s);
}
return '{'.implode(',',$arr).'}';
}
else{
$o = str_replace('\\','\\\\',$o);
$o = str_replace('"','\\"',$o);
$o = str_replace("\n",'\\n',$o);
$o = str_replace("\r",'\\r',$o);
$o = str_replace("\t",'\\t',$o);
return '"'.$o.'"';
}
}
/**
* XML serialization
* @param mixed $o
* @return string
*/
function xml_serialize($o){
if(is_array($o)){
$ret = "\n";
foreach($o as $k=>$s){
$ret .= "\n- ".$this->xml_serialize($s).'
';
}
$ret .= "\n";
return $ret;
}
else if(is_object($o)){
$ret = "\n";
return $ret;
}
else{
return htmlspecialchars($o);
}
}
}
?>