2010-07-12 115 views
8

我需要將UTF-8中的文本轉換爲ISO-8859-1編碼的文本,這樣任何不屬於ISO-8859-1集的字符都會變成字符引用。 (前β在PHP中將utf8轉換爲latin1。 255以上的所有字符轉換爲字符引用

例子:我想變成像

hello é β 水 

文本

hello é β 水 

我做的這一切在PHP。我嘗試了內置函數,iconv,以及這些的整理和組合,仍然無法獲得可靠的解決方案。

這裏是我迄今爲止

// convert any characters fount in the entity table into HTML entities 
// do not double encode entities, do not mess with quotes 
// use UTF-8 as character encoding because the page submits UTF-8 
$str = htmlentities($str,ENT_NOQUOTES,'UTF-8',false); 
//print $str."\n"; 

// convert text from UTF-8 to ISO-8859-1, 
// characters that cannot be converted will be converted to ? 
$str = utf8_decode($str); 
//print $str."\n";  

// make string XML valid. 
// mainly it converts text entities into numeric entities. 
$opts = array( "output-xhtml"  => true, 
      "output-xml"  => true, 
      "show-body-only" => true, 
      "numeric-entities" => true, 
      "wrap"    => 0, 
      "indent"   => false, 
      "char-encoding" => 'latin1' 
     ); 
$tidy = tidy_parse_string($str, $opts,'latin1'); 
tidy_clean_repair($tidy); 
$str = tidy_get_output($tidy);  
//print $str."\n"; 
+0

使用'ヶ輛( '你好éβ水',ENT_COMPAT「 UTF-8'),你至少可以將'é'和'β'轉換爲HTML實體(命名實體)。 – NikiC 2010-07-12 20:15:05

+0

當然這還不夠。最後一個字符是這裏的主要問題。請不要在最終結果(XML數據)中不允許實體,並且我希望將ISO-8859-1設置爲字符。 – 2010-07-12 20:51:38

回答

11

你需要支持多字節。特別是,mb_encode_numericentity()

$convmap= array(0x0100, 0xFFFF, 0, 0xFFFF); 
$encutf= mb_encode_numericentity($utf, $convmap, 'UTF-8'); 
$iso= utf8_decode($encutf); 

(這不接觸<&"等等,所以你可能還需要事先htmlspecialchars()

+0

非常感謝。我不知道我以前沒有注意到這些功能。 – 2010-07-12 21:52:51

+0

不好意思的是,mb函數並不是默認編譯的一部分,所以並不總是在任何地方都可用。儘管如此,我希望在大多數服務器上都能看到它們。 – bobince 2010-07-12 22:01:59

+0

謝謝。它像一個魅力。 – 2013-04-11 16:10:01