json_encode将Unicode(版权)字符的字符串编码为null?

use*_*896 5 php unicode json character-encoding

我遇到了JSON编码特殊字符的问题.这些字符通常在我的计算机,记事本,浏览器甚至数据库中显示.但是,它们不是JSON编码.一个例子如下:

<?
$array['copyright_str'] = "Copyright site.com © 2011-2012";
echo json_encode($array);
?>
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

我想避免保存类似的东西&copy;.其中一些数据将以纯文本格式存储.

Sak*_*tel 11

在将数据传递给json_encode函数之前,以UTF-8格式对数据进行编码

<?
    $array['copyright_str'] = utf8_encode("Copyright site.com © 2011-2012");
    echo json_encode($array);
?>
Run Code Online (Sandbox Code Playgroud)

  • 但是,这确实假设您将所有数据存储和处理为ISO-8859-1,这意味着您的应用程序将不支持该编码之外的Unicode字符.从长远来看,您最好完全迁移到UTF-8. (2认同)
  • 嗯...请记住,`mb_detect_encoding`只是一个近似猜测,很容易出错,是的. (2认同)