json_encode 有效
使用 UTF-8 編碼
字串僅限。如果您需要成功建立有效的json
來自 ANSI 編碼
字串,您需要先將其重新編碼/轉換為UTF-8。
然後json_encode將會
只需按照記錄進行操作即可。 要從ANSI轉換編碼(更多
正確的是,我假設您有Windows-1252 編碼
字串,很流行但被錯誤地稱為ANSI)
給UTF-8你
可以使用mb_convert_encoding()函數:$str = mb_convert_encoding($str,"UTF-8","Windows-1252");PHP中另一個可以轉換字串編碼/字元集的函數稱為iconv
onlibiconv。你也可以使用它:$str = iconv("CP1252","UTF-8", $str);關於utf8_encode()的注意事項utf8_encode() does
only work for Latin-1,
not for ANSI.
So you will destroy part of your characters inside that string when you run it through that function.Related: What is ANSI format?For a more fine-grained control of what json_encode() returns,
see the list of predifined constants(PHP version dependent, incl. PHP 5.4, some constants
remain undocumented and are available in the source code only so far).Changing the encoding of an array/iteratively (PDO comment)As you wrote in a comment that you have problems to apply the function onto an array, here is some code example. It's always needed to first change
the encoding before using json_encode.
That's just a standard array operation, for the simpler case of pdo::fetch() a foreach iteration:while($row = $q->fetch(PDO::FETCH_ASSOC)){foreach($row as&$value){
$value = mb_convert_encoding($value,"UTF-8","Windows-1252");}
unset($value);# safety: remove reference
$items[]= array_map('utf8_encode', $row );}