/** * Encode a Json while providing encoding functionnalities. * * Options may contain: * - *from_encoding* * /default to "UTF-8"/ * Encoding of the source array * - *to_encoding* * /default to "UTF-8"/ * Encoding of the returned string (JSON is serialize in UTF-8 and then encoded) * - *pretty* * /default to boolean "false"/ * Format a JSON string with carriage returns and tabulations * * @param array $array Array to encode * @param array $options[optional] Options used to alter the method behavior * * @return string Encoded JSON string */ public static function encode(array $array,array $options=array()){ if(!isset($options['from_encoding'])) $options['from_encoding'] = 'UTF-8'; if(!isset($options['to_encoding'])) $options['to_encoding'] = 'UTF-8'; if(strtoupper($options['from_encoding'])!='UTF-8') $array = PurArray::encode($array,'UTF-8',$options['from_encoding']); $array = json_encode($array); if(isset($options['pretty'])){ $array = PurJson::pretty($array); } if(strtoupper($options['to_encoding'])!='UTF-8') $array = mb_convert_encoding($array,$options['to_encoding'],'UTF-8'); return $array; }
/** * Serialize an array to a file. Unless provided, the serialization * format is derived from the file path extension. * * Options include: * - format Serialization method (js and json accepted); * - from_encoding Encoding of the provided array * - to_encoding Encoding of the destination file * * Javascript is meant to be understood as JSON surrounded by parenthesis, not * as the full Javascript language. This form is usefull when text editors * support the Javascript synthax and not the JSON one. * * JSON imposes the UTF-8 encoding. When converting to/from it, it is not the * PHP array which is encoded/decoded but the JSON string. Also, always * provide the source encoding when reading from a file written in a * different encoding than UTF-8. * * @return boolean True on success * @param string $path Path to the destination file * @param array $array Array to serialize * @param array $options[optional] */ public static function write($path,array $array,array $options=array()){ $options = self::sanitize($options); if(!isset($options['format'])){ $dot = strrpos(basename($path),'.'); if($dot===false) throw new Exception('Format Undertermined From Path: "'.basename($path).'"'); $format = substr(basename($path),$dot+1); } switch($format){ case 'json': $array = PurJson::encode($array,$options); break; case 'js': $array = PurJson::encode($array,$options); $array = '('.$array.')'; break; default: throw new Exception('Unsupported Format: "'.$format.'"'); } return PurFile::write($path,$array,$options); }