2017-10-20 78 views
1

爲Unicode當我使用json_encode編碼西班牙字符它改變了他們這樣的:轉換西班牙字符用PHP

áéíóú¿¡üñ 

要這樣:

\u00e1\u00e9\u00ed\u00f3\u00fa\u00bf\u00a1\u00fc\u00f1 

當我使用此代碼:

$str = array(); 
$str[] = 'áéíóú¿¡üñ'; 
$str[] = 'áéíóú¿¡üñ'; 
$json_data = json_encode($str); 

我的問題是如何在使用json_encode之前將字符轉換爲這種格式?如何將字符轉換爲我認爲unicode(?)格式,如圖所示,而不使用json_encode?

iconv() 

,然後轉換UTF-8字符串到十六進制:

+0

試試json_encode($ str,JSON_UNESCAPED_UNICODE); – user1844933

+0

對不起,如果我的問題不清楚 - 我想編碼西班牙字符到unicode而不使用json_encode - 我認爲必須有一個PHP函數這樣做,但我找不到它 –

+0

如果你想通用字符支持,最簡單事實上是使用'json_encode':'substr(json_encode($ str),1,-1)'。否則,您需要定義如何處理BMP以外的字符; JSON已經定義了它...... – deceze

回答

0

是的,你可以通過字符串轉換爲UTF-8實現這一

bin2hex() 

轉換後,您將需要處理每個字符的編碼順序 - 下面是一個例子:

<?php 
$spanishCharacterString = 'áéíóú¿¡üñ'; 

/* Convert the string to UTF-8 and then into hexadecimal */ 
$encodedSpanishCharacterString = bin2hex(iconv('UTF-8', 'UCS-2', $spanishCharacterString)); 

/* Break string into individual characters */ 
$spanishCharacterArray = str_split($encodedSpanishCharacterString, 4); 

/* Format the encoding of each character */ 
for ($i = 0; $i < count($spanishCharacterArray); $i++) { 
    $spanishCharacterArray[$i] = '\u'.substr($spanishCharacterArray[$i], -2, 2).substr($spanishCharacterArray[$i], 0, 2); 
} 

/* Join the encoded characters back up again */ 
$convertedSpanishCharacterString = implode($spanishCharacterArray); 

echo $convertedSpanishCharacterString; 

?> 
+0

請注意,這不適用於BMP以上的字符,比如表情符號。 – deceze

+1

哪個表情符號是「西班牙字符」? ;-) – Rounin

+3

很明顯: – deceze