解决方案非常复杂。
解决方案分为 3 部分: 第 1 部分:安装 FPDF 中文插件 第 2 部分:将 NCR 格式转换为 UTF-8 第 3 部分:将 UTF-8 格式转换为 BIG5(或任何目标编码)
第1部分
我从这里获取了 FPDF 中文插件:http ://dev.xoofoo.org/modules/content/d1/d6e/a00073.html
用于在 FPDF 中显示汉字,并获取所有需要的中文字体。要安装此插件,只需将其包含在 PHP 中即可。(但就我而言,我使用了另一个名为 CellPDF 的插件,它与这个中文插件一起崩溃;因此,我必须合并代码并解决冲突)
第2部分
要将 NCR 格式转换为 UTF-8,我使用以下代码:
function html_entity_decode_utf8($string)
{
static $trans_tbl;
// replace numeric entities
$string = preg_replace('~&#x([0-9a-f]+);~ei', 'code2utf(hexdec("\\1"))', $string);
$string = preg_replace('~&#([0-9]+);~e', 'code2utf(\\1)', $string);
// replace literal entities
if (!isset($trans_tbl))
{
$trans_tbl = array();
foreach (get_html_translation_table(HTML_ENTITIES) as $val=>$key)
$trans_tbl[$key] = utf8_encode($val);
}
return strtr($string, $trans_tbl);
}
function code2utf($num)
{
if ($num < 128) return chr($num);
if ($num < 2048) return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
if ($num < 65536) return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
if ($num < 2097152) return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
return '';
}
由 php.net 的 laurynas butkus 编写(链接:http ://www.php.net/manual/en/function.html-entity-decode.php )虽然这段代码本身将 NCR 格式转换为“怪物字符” “,我知道这是一个好的开始。
第 3 部分
在我深入 php.net 之后,我发现了一个不错的函数:iconv,用于转换编码。所以我用以下函数包装了上面的代码:
function ncr_decode($string, $target_encoding='BIG5') {
return iconv('UTF-8', 'BIG5', html_entity_decode_utf8($string));
}
因此,如果我想转换上一行 NCR 字符串,我只需要运行这个函数:
ncr_decode("這個一個例子");
ps 默认情况下,我将目标编码设置为BIG5。
就是这样!