Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Using json_encode() with some character sets can result in false being returned.
- * These functions allow creation of JSON strings from any value/object that may need
- * UTF-8 encoding.
- */
- /**
- * Given the output from serialize(), this will encode or decode UTF-8 characters
- * and adjust length markers as necessary.
- *
- * @param string $input The input string
- * @param boolean $encode Are we encoding (or decoding) the string
- * @return string
- */
- function utf8Adjust($input, $encode=TRUE) {
- if (preg_match('//u', $input) === 1) {
- // Already using UTF-8, no encoding to do
- if ($encode) return $input;
- } else {
- // Not UTF-8, no decoding to do
- if (!$encode) return $input;
- }
- $output = '';
- // Copy input string characters until we get to 's' - a string, or 'O' - a class name
- for ($i=0; $i<strlen($input); ++$i) {
- $output .= $input{$i};
- if ($input{$i} === 's' || $input{$i} === 'O') {
- ++$i; // ':'
- // After 's:' or 'O:' is the length
- $length = '';
- while ($input{++$i} !== ':') {
- $length .= $input{$i};
- }
- $length = (int) $length;
- $i += 2; // ':"'
- // Now we can get the string itself
- $string = substr($input, $i, $length);
- // We can use this function to encode and decode
- $string = ($encode) ? utf8_encode($string) : utf8_decode($string);
- // Join everything back together
- $output .= ':' . strlen($string) . ':"' . $string . '"';
- $i += $length;
- }
- }
- return $output;
- }
- /**
- * UTF-8 encode an input value
- *
- * @param mixed $input
- * @return mixed
- */
- function utf8Encode($input) {
- return unserialize(utf8Adjust(serialize($input), TRUE));
- }
- /**
- * UTF-8 decode an input value
- *
- * @param mixed $input
- * @return mixed
- */
- function utf8Decode($input) {
- return unserialize(utf8Adjust(serialize($input), FALSE));
- }
- /**
- * JSON encode - handling UTF-8 encoding
- *
- * @param mixed $input
- * @return string
- */
- function jsonEncode($input) {
- return json_encode(utf8Encode($input));
- }
- /**
- * JSON decode - handling UTF-8 encoding
- *
- * @param string $input
- * @param boolean $assoc [optional] When TRUE, returned objects will be
- * converted into associative arrays.
- * @param integer $depth [optional] User specified recursion depth.
- * @param integer $options [optional] Bitmask of JSON decode options.
- * Currently only JSON_BIGINT_AS_STRING is supported (default is to cast
- * large integers as floats)
- * @return mixed
- */
- function jsonDecode($input, $assoc=FALSE, $depth=512, $options=0) {
- return utf8Decode(json_decode($input, $assoc, $depth, $options));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement