=')) { return json_last_error_msg(); } // All possible error codes before PHP 5.5.0 (except JSON_ERROR_NONE) switch (json_last_error()) { case JSON_ERROR_DEPTH: return 'Maximum stack depth exceeded'; case JSON_ERROR_STATE_MISMATCH: return 'State mismatch (invalid or malformed JSON)'; case JSON_ERROR_CTRL_CHAR: return 'Control character error, possibly incorrectly encoded'; case JSON_ERROR_SYNTAX: return 'Syntax error'; case JSON_ERROR_UTF8: return 'Malformed UTF-8 characters, possibly incorrectly encoded'; default: return 'Unknown error'; } } /** * Replace bad byte sequences in UTF-8 strings inside the given JSON-encodable structure with question marks * * @param mixed $value * * @return mixed */ protected static function sanitizeUtf8Recursive($value) { switch (gettype($value)) { case 'string': return static::sanitizeUtf8String($value); case 'array': $sanitized = array(); foreach ($value as $key => $val) { if (is_string($key)) { $key = static::sanitizeUtf8String($key); } $sanitized[$key] = static::sanitizeUtf8Recursive($val); } return $sanitized; case 'object': $sanitized = array(); foreach ($value as $key => $val) { if (is_string($key)) { $key = static::sanitizeUtf8String($key); } $sanitized[$key] = static::sanitizeUtf8Recursive($val); } return (object) $sanitized; default: return $value; } } /** * Replace bad byte sequences in the given UTF-8 string with question marks * * @param string $string * * @return string */ protected static function sanitizeUtf8String($string) { return mb_convert_encoding($string, 'UTF-8', 'UTF-8'); } }