[英]php utf-8 encoding problems
大家好:我在這里遇到了一個棘手的問題:我需要讀取一些文件並將其內容轉換為一些 XML 文件。 對於文件中的每一行,我相信它們中的大多數都是有效的 ASCII 代碼,因此我可以將該行讀入 php 並將該行保存到一個 XML 文件中,默認編碼 XML 為“UTF-8”。 但是,我注意到原始文件中可能存在一些GBK,GB2312(漢字),SJIS(日文字符)等。php直接將字符串保存到XML中沒有問題。 但是,XML 解析器會檢測到無效的 UTF-8 代碼並崩潰。
現在,我認為最適合我的庫 php 函數可能是:
$decode_str = mb_convert_encoding($str, 'UTF-8', 'auto');
在將其插入 XML 之前,我嘗試為每一行運行此對話功能。 但是,當我用一些 UTF-16 和 GBK 編碼進行測試時,我認為這個函數不能正確區分輸入字符串編碼模式。
另外,我嘗試使用 CDATA 來包裝字符串,奇怪的是 XML 解析器仍然抱怨無效的 UTF-8 代碼等等。當然,當我 vim xml 文件時,CDATA 里面的內容肯定是一團糟。
有什么建議?
我曾經花了很多時間來創建一個安全的UTF8 編碼函數:
function _convert($content) {
if(!mb_check_encoding($content, 'UTF-8')
OR !($content === mb_convert_encoding(mb_convert_encoding($content, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {
$content = mb_convert_encoding($content, 'UTF-8');
if (mb_check_encoding($content, 'UTF-8')) {
// log('Converted to UTF-8');
} else {
// log('Could not be converted to UTF-8');
}
}
return $content;
}
主要問題是找出輸入字符串已經使用了哪種編碼。 請告訴我我的解決方案是否也適用於您!
我在使用 json_encode 時遇到了這個問題。 我用它來把所有東西都變成 utf8。 來源: http : //us2.php.net/manual/en/function.json-encode.php
function ascii_to_entities($str)
{
$count = 1;
$out = '';
$temp = array();
for ($i = 0, $s = strlen($str); $i < $s; $i++)
{
$ordinal = ord($str[$i]);
if ($ordinal < 128)
{
if (count($temp) == 1)
{
$out .= '&#'.array_shift($temp).';';
$count = 1;
}
$out .= $str[$i];
}
else
{
if (count($temp) == 0)
{
$count = ($ordinal < 224) ? 2 : 3;
}
$temp[] = $ordinal;
if (count($temp) == $count)
{
$number = ($count == 3) ? (($temp['0'] % 16) * 4096) +
(($temp['1'] % 64) * 64) +
($temp['2'] % 64) : (($temp['0'] % 32) * 64) +
($temp['1'] % 64);
$out .= '&#'.$number.';';
$count = 1;
$temp = array();
}
}
}
return $out;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.