使用PHP/COM将UTF-8字符串写入Word


Writing UTF-8 strings to Word using PHP/COM

我正试图使用PHP/COM从MySQL数据库中生成一个Word文档。如果数据库中的数据是简单的ASCII文本(例如"hello"),则它会在Word文档中正确显示。如果数据包含非ASCII(多字节)字符(例如"Māori"),则它们显示正确,但末尾有"有趣"字符(如NULL、空格或中文符号)。

环境:我使用的是Windows 7 Enterprise、Apache、MySQL、PHP 5.2.17和Microsoft Office 2010。

这里有一个简化的例子-我甚至不使用数据库或写入Word文档,而是简单地使用WordCleanString方法来重现问题:

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使用原始字符串中的字节数作为返回字符串中的字符数。

原来这是一个PHP错误(https://bugs.php.net/bug.php?id=66431)已在PHP 5.4.29中修复。我用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.