2011-03-04 57 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; 
} 

的主要问题是要弄清楚其编码输入的字符串已使用。请告诉我我的解决方案是否也适用于您!