如何在PHP中将此数组转换为JSON [英] How to convert this array into JSON in PHP

查看:98
本文介绍了如何在PHP中将此数组转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了很多关于该主题的文章,并且尝试了许多解决方案,但无法将此多数组转换为JSON字符串.这是我print_r($result):

时看到的内容

Array ( [profiles] => 
       Array ( [0] => 
              Array ( [ID] => 00000000-0000-0000-0000-000000000001 
                      [UserName] => Administrator GU 
                      [Age] => 37 
                      [CityStateCode] => Montréal 
                      [OnlineSince] => En ligne depuis 6 heures 39 minutes 
                      [IsPaying] => true 
                      [LabelOnlineStatus] => En ligne 
                    ) 
               [1] => 
              Array ( [ID] => ab3dd04e-5621-11e3-b448-103f0c805f5a 
                      [UserName] => Guillaume Le Genie 
                      [Age] => 68 
                      [CityStateCode] => Montréal 
                      [OnlineSince] => En ligne depuis 1 jour 9 heures 
                      [IsPaying] => true 
                      [LabelOnlineStatus] => Hors-Ligne 
                    ) 
               [2] => 
              Array ( [ID] => 00000000-0000-0000-0000-000000000050 
                      [UserName] => Baby-dragoon 
                      [Age] => 25 
                      [CityStateCode] => Québec 
                      [OnlineSince] => En ligne depuis 5 jours 6 heures 
                      [IsPaying] => true 
                      [LabelOnlineStatus] => Hors-Ligne 
                    ) 
            )      
      )

我尝试使用此方法(有或没有true参数):

$result = json_encode($result, true);
$error = json_last_error_msg();
echo "[ERROR : $error]-----[$result]-----";

我收到:

[ERROR : Malformed UTF-8 characters, possibly incorrectly encoded]-----[]-----

当我尝试此操作时:

$result = json_encode(htmlspecialchars(utf8_encode($result)));

我收到:

警告:utf8_encode()希望参数1为字符串,在 2839 行中的/Applications/XAMPP/xamppfiles/htdocs/cdn/php/functionsv1.php 中给出>
[错误:没有错误] ----- ["] -----

当我尝试此操作时:

$result = json_encode(htmlspecialchars($result));

我收到:

警告:htmlspecialchars()期望参数1为字符串,在 2839 行上的/Applications/XAMPP/xamppfiles/htdocs/cdn/php/functionsv1.php 中给出>
[错误:没有错误] ----- [空] -----

我真的迷路了!

您会看到语言是法语,所以我们有一个带有重音符号的字符,例如éèàô等...

从MySQL数据库提供的数据和数据库设置为:

mysql_query("SET NAMES 'utf8'");
mysql_query('SET CHARACTER SET utf8');

解决方案

我正在运行PHP 5.4.7,对我来说,以下代码可以完美运行:

$result = json_encode($result, true);

我知道您已经尝试过了.莱昂纳多的建议也对我有用:

$result = json_encode($result, JSON_UNESCAPED_UNICODE);

问题在于,在PHP 5.5.0中,json_encode要求字符串为UTF-8.


所以..您将必须传递有效的utf8字符串,该如何执行取决于您的字符串所采用的编码.您以为您需要utf8_encode或类似函数是正确的.您可能还想看看 iconv .

现在utf8_encode的问题在于此函数不适用于数组,因为您需要一个辅助函数,例如:

function utf8_encode_recursive ($array)
{
    $result = array();
    foreach ($array as $key => $value)
    {
        if (is_array($value))
        {
            $result[$key] = utf8_encode_recursive($value);
        }
        else if (is_string($value))
        {
            $result[$key] = utf8_encode($value);
        }
        else
        {
            $result[$key] = $value;
        }
    }
    return $result;
}

注1:utf8_encode仅接受ISO-8859-1中的字符串.验证您使用的是哪种编码.

注2:htmlspecialcharshtmlentities不会转换编码的所有字符,仅转换那些危险"字符(htmlspecialchars)或具有html等效命名实体(htmlentities)的字符.对于此用例,请使用 mb_encode_numericentity .

注释3: iconv mb_encode_numericentity 将允许您指定字符串的编码.此外,它们也不能与数组一起使用,因此您也需要为它们编写递归帮助器函数.

I read many many many posts on this subject and I tried many solutions and I can't convert this multi-array into a JSON string. This is what I see when I print_r($result):

Array ( [profiles] => 
       Array ( [0] => 
              Array ( [ID] => 00000000-0000-0000-0000-000000000001 
                      [UserName] => Administrator GU 
                      [Age] => 37 
                      [CityStateCode] => Montréal 
                      [OnlineSince] => En ligne depuis 6 heures 39 minutes 
                      [IsPaying] => true 
                      [LabelOnlineStatus] => En ligne 
                    ) 
               [1] => 
              Array ( [ID] => ab3dd04e-5621-11e3-b448-103f0c805f5a 
                      [UserName] => Guillaume Le Genie 
                      [Age] => 68 
                      [CityStateCode] => Montréal 
                      [OnlineSince] => En ligne depuis 1 jour 9 heures 
                      [IsPaying] => true 
                      [LabelOnlineStatus] => Hors-Ligne 
                    ) 
               [2] => 
              Array ( [ID] => 00000000-0000-0000-0000-000000000050 
                      [UserName] => Baby-dragoon 
                      [Age] => 25 
                      [CityStateCode] => Québec 
                      [OnlineSince] => En ligne depuis 5 jours 6 heures 
                      [IsPaying] => true 
                      [LabelOnlineStatus] => Hors-Ligne 
                    ) 
            )      
      )

I try this (with and without true parameter):

$result = json_encode($result, true);
$error = json_last_error_msg();
echo "[ERROR : $error]-----[$result]-----";

And I receive:

[ERROR : Malformed UTF-8 characters, possibly incorrectly encoded]-----[]-----

When I try this:

$result = json_encode(htmlspecialchars(utf8_encode($result)));

I receive:

Warning: utf8_encode() expects parameter 1 to be string, array given in /Applications/XAMPP/xamppfiles/htdocs/cdn/php/functionsv1.php on line 2839
[ERROR : No error]-----[""]-----

When I try this:

$result = json_encode(htmlspecialchars($result));

I receive:

Warning: htmlspecialchars() expects parameter 1 to be string, array given in /Applications/XAMPP/xamppfiles/htdocs/cdn/php/functionsv1.php on line 2839
[ERROR : No error]-----[null]-----

I'm really lost!

N.B. You see the language is French so we have a char with accent like éèàô etc...

The data provide from MySQL Database and database is set to:

mysql_query("SET NAMES 'utf8'");
mysql_query('SET CHARACTER SET utf8');

解决方案

I am running PHP 5.4.7, for me the following code works flawlessly:

$result = json_encode($result, true);

I know you have already tried that. Leonardo's suggestion also works for me:

$result = json_encode($result, JSON_UNESCAPED_UNICODE);

The issue is that in PHP 5.5.0 json_encode requires the strings to be UTF-8.


So.. you will have to pass a valid utf8 string, how to do it depend on what encoding you have your strings in. You are right in thinking you need utf8_encode or similar function. You may also want to give a look to iconv.

Now the issue with utf8_encode is that this function will not work with arrays, for that you need a helper function, such as:

function utf8_encode_recursive ($array)
{
    $result = array();
    foreach ($array as $key => $value)
    {
        if (is_array($value))
        {
            $result[$key] = utf8_encode_recursive($value);
        }
        else if (is_string($value))
        {
            $result[$key] = utf8_encode($value);
        }
        else
        {
            $result[$key] = $value;
        }
    }
    return $result;
}

Note 1: utf8_encode only accepts strings in ISO-8859-1. Verify what encoding you are using.

Note 2: htmlspecialchars and htmlentities will not convert all the characters of your encoding, only those "dangerous" (htmlspecialchars) or that have html equivalent named entities (htmlentities). For this use case use mb_encode_numericentity instead.

Note 3: Both iconv and mb_encode_numericentity will allow you to specify the encoding of your string. Also they don't work with arrays either, so you will need to write recursive helper functions for them too.

这篇关于如何在PHP中将此数组转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆