/** * Encodes a PHP value into a JSON string * * @param mixed $value The PHP value to encode * @return string The JSON string that is equivalent to the PHP value */ public static function encode($value) { if (is_resource($value)) { return 'null'; } if (function_exists('json_encode')) { return json_encode($value); } if (is_int($value)) { return (string) $value; } if (is_float($value)) { return (string) $value; } if (is_bool($value)) { return $value ? 'true' : 'false'; } if (is_null($value)) { return 'null'; } if (is_string($value)) { if (!preg_match('#^.*$#usD', $value)) { return 'null'; } $char_array = fUTF8::explode($value); $output = '"'; foreach ($char_array as $char) { if (isset(self::$control_character_map[$char])) { $output .= self::$control_character_map[$char]; } elseif (strlen($char) < 2) { $output .= $char; } else { $output .= '\\u' . substr(strtolower(fUTF8::ord($char)), 2); } } $output .= '"'; return $output; } // Detect if an array is associative, which would mean it needs to be encoded as an object $is_assoc_array = FALSE; if (is_array($value) && $value) { $looking_for = 0; foreach ($value as $key => $val) { if (!is_numeric($key) || $key != $looking_for) { $is_assoc_array = TRUE; break; } $looking_for++; } } if (is_object($value) || $is_assoc_array) { $output = '{'; $members = array(); foreach ($value as $key => $val) { $members[] = self::encode((string) $key) . ':' . self::encode($val); } $output .= join(',', $members); $output .= '}'; return $output; } if (is_array($value)) { $output = '['; $members = array(); foreach ($value as $key => $val) { $members[] = self::encode($val); } $output .= join(',', $members); $output .= ']'; return $output; } }