我在JSON编码特殊字符时遇到了麻烦。这些字符在我的电脑、记事本、浏览器甚至数据库中都能正常显示,但是它们无法进行JSON编码。以下是一个示例:
<?
$array['copyright_str'] = "Copyright site.com © 2011-2012";
echo json_encode($array);
?>
在site.com之后的版权符号是导致JSON字符串输出为{"copyright_str":null}
的原因。虽然这很简单,但我有用户将个人资料数据输入到数据库中,其中可能包含任何内容。当这些奇怪的字符出现时,会破坏事情的正常运行。有什么好的解决方案吗?我编写的API在很大程度上依赖于从数据库返回数据和以JSON形式打印字符串。
我的多字节设置如下:
php -e phpinfo.php | grep mb
Configure Command => './configure' '--enable-bcmath' '--enable-calendar' '--enable-dbase' '--enable-exif' '--enable-ftp' '--enable-gd-native-ttf' '--enable-libxml' '--enable-magic-quotes' '--enable-mbstring' '--enable-pdo=shared' '--enable-sockets' '--enable-zip' '--prefix=/usr/local' '--with-apxs2=/usr/local/apache/bin/apxs' '--with-bz2' '--with-curl=/opt/curlssl/' '--with-curlwrappers' '--with-freetype-dir=/usr' '--with-gd' '--with-imap=/opt/php_with_imap_client/' '--with-imap-ssl=/usr' '--with-jpeg-dir=/usr' '--with-kerberos' '--with-libdir=lib64' '--with-libexpat-dir=/usr' '--with-libxml-dir=/opt/xml2/' '--with-mcrypt=/opt/libmcrypt/' '--with-mhash=/opt/mhash/' '--with-mysql=/usr' '--with-mysql-sock=/var/lib/mysql/mysql.sock' '--with-mysqli=/usr/bin/mysql_config' '--with-openssl=/usr' '--with-openssl-dir=/usr' '--with-pcre-regex=/opt/pcre' '--with-pdo-mysql=shared' '--with-pdo-sqlite=shared' '--with-pic' '--with-png-dir=/usr' '--with-sqlite=shared' '--with-ttf' '--with-xmlrpc' '--with-xpm-dir=/usr' '--with-zlib' '--with-zlib-dir=/usr'
xmlrpc_error_number => 0 => 0
mbstring
Multibyte string engine => libmbfl
mbstring extension makes use of "streamable kanji code filter and converter", which is distributed under the GNU Lesser General Public License version 2.1.
mbstring.detect_order => no value => no value
mbstring.encoding_translation => Off => Off
mbstring.func_overload => 0 => 0
mbstring.http_input => pass => pass
mbstring.http_output => pass => pass
mbstring.internal_encoding => no value => no value
mbstring.language => neutral => neutral
mbstring.strict_detection => Off => Off
mbstring.substitute_character => no value => no value
我希望避免保存像
©
这样的内容。其中一些数据将以纯文本形式存储。
json_encode
在Unicode/MB上是否能正常工作? - user166390