Php转换为ISO-8859-9

时间:2009-06-15 08:43:49

标签: php json utf-8 character-encoding

我使用JSON对数组进行编码,我得到一个这样的字符串:

{"name":"\u00fe\u00fd\u00f0\u00f6\u00e7"}

现在我需要将其转换为ISO-8859-9。我尝试了以下但它失败了:

header('Content-type: application/json; charset=ISO-8859-9');
$json = json_encode($response);
$json = utf8_decode($json);
$json = mb_convert_encoding($json, "ISO-8859-9", "auto");
echo $json;

它似乎无法奏效。我错过了什么?

感谢您的时间。

2 个答案:

答案 0 :(得分:2)

你可以这样做:

$json = json_encode($response);
header('Content-type: application/json; charset=ISO-8859-9');
echo mb_convert_encoding($json, "ISO-8859-9", "UTF-8");

假设$response中的字符串是utf-8。但我强烈建议你一直使用utf-8。

编辑:对不起,刚刚意识到这将无效,因为json_encode将unicode点作为javascript转义码转义。您必须先将这些转换为utf-8序列。我不认为有任何内置功能,但您可以使用稍微修改后的this library变体来实现。请尝试以下方法:

function unicode_hex_to_utf8($hexcode) {
  $arr = array(hexdec(substr($hexcode[1], 0, 2)), hexdec(substr($hexcode[1], 2, 2)));
  $dest = '';
  foreach ($arr as $src) {
    if ($src < 0) {
      return false;
    } elseif ( $src <= 0x007f) {
      $dest .= chr($src);
    } elseif ($src <= 0x07ff) {
      $dest .= chr(0xc0 | ($src >> 6));
      $dest .= chr(0x80 | ($src & 0x003f));
    } elseif ($src == 0xFEFF) {
      // nop -- zap the BOM
    } elseif ($src >= 0xD800 && $src <= 0xDFFF) {
      // found a surrogate
      return false;
    } elseif ($src <= 0xffff) {
      $dest .= chr(0xe0 | ($src >> 12));
      $dest .= chr(0x80 | (($src >> 6) & 0x003f));
      $dest .= chr(0x80 | ($src & 0x003f));
    } elseif ($src <= 0x10ffff) {
      $dest .= chr(0xf0 | ($src >> 18));
      $dest .= chr(0x80 | (($src >> 12) & 0x3f));
      $dest .= chr(0x80 | (($src >> 6) & 0x3f));
      $dest .= chr(0x80 | ($src & 0x3f));
    } else {
      // out of range
      return false;
    }
  }
  return $dest;
}

print mb_convert_encoding(
  preg_replace_callback(
    "~\\\\u([1234567890abcdef]{4})~", 'unicode_hex_to_utf8',
    json_encode($response)),
  "ISO-8859-9", "UTF-8");

答案 1 :(得分:1)

正如您在PHP documentation site JSON编码/解码函数中看到的那样,只能使用utf8编码,因此尝试更改此操作会导致一些数据问题,您可能会遇到意外和错误的结果。

相关问题