2009-06-15 54 views
0

我使用JSON編碼一個數組,我得到一個字符串是這樣的:腓轉換爲ISO-8859-9

{"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; 

它似乎沒有工作。我錯過了什麼?

謝謝你的時間。

+0

因此,您的JSON數據在'$ response`中? – Gumbo 2009-06-15 08:46:28

+0

$ response是一個數組,其中包含我在json_encode上執行的數據。 – 2009-06-15 08:47:22

回答

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

正如你在PHP documentation site上看到的那樣,JSON編碼/解碼函數只能用於utf8編碼,所以試圖改變它會導致你一些數據問題,你可能會得到意想不到的結果。

+0

我有從JSON(這是在UTF8)的輸出後,我不能將它轉換爲'ISO-8859-9'? – 2009-06-15 08:59:47