2011-03-04 60 views
1

大家好: 我遇到了一個棘手的問題:我需要讀取一些文件並將其內容轉換爲一些XML文件。對於文件中的每一行,我相信它們中的大多數都是有效的ASCII碼,這樣我就可以將該行讀入php中,並將該行保存爲默認編碼XML爲'UTF-8'的XML文件。但是,我注意到原始文件中可能存在GBK,GB2312(中文字符),SJIS(日文字符)等等,php將字符串直接保存爲XML沒有問題。但是,XML解析器將檢測到存在無效的UTF-8代碼並崩潰。php utf-8編碼問題

現在,我想我的目的最好的圖書館PHP函數大概是:

$decode_str = mb_convert_encoding($str, 'UTF-8', 'auto'); 

我試着將它插入XML之前運行的每一行此對話功能。然而,正如我測試了一些UTF-16和GBK編碼,我不認爲這個函數可以正確區分輸入字符串編碼模式。另外,我試圖用CDATA來包裝字符串,奇怪的是XML解析器仍然抱怨無效的UTF-8編碼等等。當然,當我vim xml文件時,CDATA裏面是什麼肯定是一塌糊塗。

有什麼建議嗎?

+0

你試過iconv()函數嗎? – Edmhs 2011-03-04 08:00:10

回答

0

我在使用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; 
    } 
2

我曾經花了很多時間來創造一個安全UTF8 encoding function

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; 
} 

的主要問題是要弄清楚其編碼輸入的字符串已使用。請告訴我我的解決方案是否也適用於您!