我正在尝试使用来自MySQL数据库的数据使用PHP / COM生成Word文档。如果数据库中的数据是简单的ASCII文本(例如“hello”),它将在Word文档中正确显示。如果数据包含非ASCII(多字节)字符(例如“毛利”),它们会正确显示,但最后会有“搞笑”字符(例如NULL,空格或中文符号) )。
环境:我使用的是Windows 7企业版,Apache,MySQL,PHP 5.2.17和Microsoft Office 2010。
这是一个简化的示例 - 我甚至不使用数据库或写入Word文档,而只是使用Word CleanString 方法来重现问题:
private function _cleanString($wordApp, $str)
{
$vStr = new VARIANT($str, VT_BSTR, CP_UTF8);
$bytes = strlen($vStr);
$chars = mb_strlen($vStr, "UTF-8");
echo "Test string: $vStr (bytes=$bytes, chars=$chars)<br/>";
$vStr = $wordApp->CleanString($vStr);
$bytes = strlen($vStr);
$chars = mb_strlen($vStr, "UTF-8");
echo "Test string (after cleaning): $vStr (bytes=$bytes, chars=$chars)<br/>";
echo "<br/>";
}
public function testUtf8Strings()
{
com_load_typelib('Word.Application');
// Specifying codepage as CP_UTF8 to let COM/Word know strings I pass in will be in UTF-8 format.
$wordApp = new COM("word.application", null, CP_UTF8) or die ("couldn't create an instance of word");
echo "Loaded Word, version {$wordApp->Version} <br/>";
$wordApp->visible = false;
echo "<br/>";
$this->_cleanString($wordApp, 'No multi-byte characters.');
$this->_cleanString($wordApp, 'Multi-byte chars: Māori 楠 test.');
$this->_cleanString($wordApp, 'Multi-byte chars: Ā ā Ē ē Ī.');
$wordApp->Quit(false); // Imortant: must say 'false', otherwise Word does not close
$wordApp = null;
echo "Quit Word.";
return;
}
HTML输出是:
Loaded Word, version 14.0
Test string: No multi-byte characters. (bytes=25, chars=25)
Test string (after cleaning): No multi-byte characters. (bytes=25, chars=25)
Test string: Multi-byte chars: Māori 楠 test. (bytes=34, chars=31)
Test string (after cleaning): Multi-byte chars: Māori 楠 test. 5 (bytes=39, chars=34)
Test string: Multi-byte chars: Ā ā Ē ē Ī. (bytes=33, chars=28)
Test string (after cleaning): Multi-byte chars: Ā ā Ē ē Ī. 琠獥㔠 (bytes=46, chars=33)
Quit Word.
CleanString 方法从给定字符串中删除非打印字符,并将其更改为空格。由于我的字符串已经“干净”,我期望得到相同的字符串。当我的字符串具有多字节字符时,情况并非如此。看起来Word使用原始字符串中的字节数作为返回字符串中的字符数。
答案 0 :(得分:0)
事实证明这是PHP 5.4.29中修复的PHP错误(https://bugs.php.net/bug.php?id=66431)。我用PHP 5.5.19进行了测试,问题不再发生。 HTML输出是:
Loaded Word, version 14.0
Test string: No multi-byte characters. (bytes=25, chars=25)
Test string (after cleaning): No multi-byte characters. (bytes=25, chars=25)
Test string: Multi-byte chars: Māori 楠 test. (bytes=34, chars=31)
Test string (after cleaning): Multi-byte chars: Māori 楠 test. (bytes=34, chars=31)
Test string: Multi-byte chars: Ā ā Ē ē Ī. (bytes=33, chars=28)
Test string (after cleaning): Multi-byte chars: Ā ā Ē ē Ī. (bytes=33, chars=28)
Quit Word.