当我使用json_encode编码西班牙语字符时,它会改变它们:
áéíóú¿¡üñ
对此:
\u00e1\u00e9\u00ed\u00f3\u00fa\u00bf\u00a1\u00fc\u00f1
当我使用此代码时:
$str = array();
$str[] = 'áéíóú¿¡üñ';
$str[] = 'áéíóú¿¡üñ';
$json_data = json_encode( $str );
我的问题是在使用json_encode之前如何将字符转换为此格式?如何在不使用json_encode的情况下将字符转换为我认为的unicode(?)格式?
答案 0 :(得分:0)
是的,您可以通过将字符串转换为UTF-8
来实现此目的:
iconv()
然后将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;
?>