Press "Enter" to skip to content

A GBK-Encoded PHP Script Causing a Syntax Error (Zend Multibyte)

A friend asked me on weibo:

     Under a GBK environment, the following PHP code: <?php echo("洪仁玕");?> triggers a PHP syntax error. How to solve it?

This is because, in GBK, the encoding of "玕" is "0xab 0x5c, so this is again a problem caused by '5c'.
Generally speaking, I still recommend using Unicode as the character set for your code files. If you have to use GBK, convert it proactively beforehand.
But to address the question directly: if your script must be GBK-encoded, how do you avoid this problem?
Starting with PHP 5.3, PHP introduced Zend Multibyte to support multibyte character encodings. For the code above, we modify it as follows:

<?php
declare(encoding="cp936");
echo("洪仁玕");
?>

Then configure it in php.ini:

mbstring.internal_encoding=cp936

Or run PHP with the following command:

$php  -dmbstring.internal_encoding=cp936 test.php

This way, PHP will execute test.php using the cp936 encoding. For more information about Zend Multibyte, see: PHP: what is --enable-zend-multibyte configure option for?, PHP declare
PS: while testing PHP 5.4 RC1, I found a BUG — PHP 5.4 cannot correctly convert from GBK to UTF-8. I have since fixed it. If you run into this problem, just watch for the upcoming PHP 5.4 RC2 release. Thanks.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.