PHP警告:json_encode() [函数。json编码]:在参数中无效的UTF-8序列。

时间:2023-01-05 22:17:15

I know it's been asked a lot of times and ....

我知道这是被问了很多次,....

Yes, I searched on Google, on * and so on, but I did not solved my problem.

是的,我搜索了谷歌,*等等,但是我没有解决我的问题。

I use this script taken from the internet:

我使用互联网上的这个脚本:

<?php

// Create connection
$con=mysqli_connect("mysql.example.com","example_example","password","example_exa");

// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM Frasi";

// Check if there are results
if ($result = mysqli_query($con, $sql))
{
    // If so, then create a results array and a temporary one
    // to hold the data
    $resultArray = array();
    $tempArray = array();

    // Loop through each row in the result set
    while($row = $result->fetch_object())
    {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    // Finally, encode the array to JSON and output the results
    echo json_encode($resultArray);
}

// Close connections
mysqli_close($result);
mysqli_close($con);
?>

To get results and put them into an Array (mutable). The problem is that when I insert accented characters such as "à è ì ò ù" I get a "null" string, while the one without accented characters in correctly shown.

获取结果并将其放入数组(可变的)。问题是,当我插入重音字符(如“a ei ou”)时,会得到一个“空”字符串,而没有重音字符的字符串会被正确显示。

[{"Frasi":null},{"Frasi":"Senza accento, funziona!"}]

In PhpMyAdmin I set everything on UTF-8 and then to utf8mb4_unicode_ci ... but did not work. I tried "SET NAMES 'utf-8'" but nothing. I tried htmlentities( (string) $value, ENT_QUOTES, 'utf-8', FALSE); ... and nothing

在PhpMyAdmin中,我设置了UTF-8和utf8mb4_unicode_ci的所有内容…但没有工作。我尝试了“设置名字‘utf-8’”,但是什么都没有。我尝试了htmlentities((string) $value, ENT_QUOTES, 'utf-8', FALSE);…并没有什么

My hosting uses:

我的主机使用:

cpsrvd 11.42.1.20 Database client version: libmysql - 5.0.96 PHP extension: mysql

数据库客户端版本:libmysql - 5.0.96 PHP扩展:mysql

Server: mysql.netsons.com via TCP/IP Server type: MySQL Server version: 5.5.36-log - MySQL Community Server (GPL) Protocol version: 10 User: duxnzsje@srv-hp16.netsons.net Server charset: UTF-8 Unicode (utf8)

服务器:mysql.netsons.com通过TCP/IP服务器类型:MySQL服务器版本:5.56 -log - MySQL社区服务器(GPL)协议版本:10用户:duxnzsje@srv-hp16.net服务器字符集:UTF-8 Unicode (utf8)

Any ideas, please?

有什么想法吗?

Thanks!

谢谢!

2 个解决方案

#1


1  

From what we actually saw above, the solution should be something like this:

根据我们上面看到的,解决方案应该是这样的:

<?php

            // Create connection
            $con=mysqli_connect("mysql.example.com","example_example","password","example_exa");

            // Check connection
            if (mysqli_connect_errno())
            {
              echo "Failed to connect to MySQL: " . mysqli_connect_error();
            }

            // This SQL statement selects ALL from the table 'Locations'
            $sql = "SELECT * FROM Frasi";

            // Check if there are results
            if ($result = mysqli_query($con, $sql))
            {
                // If so, then create a results array and a temporary one
                // to hold the data
                $resultArray = array();
                $tempArray = array();

                // Loop through each row in the result set
                while($row = $result->fetch_object())
                {
                    // Add each row into our results array
                    foreach ($row as $key => $value) {
                        $tempArray[$key] = iconv(mb_detect_encoding($value), 'UTF-8', $value);
                    }
                    array_push($resultArray, $tempArray);
                    $tempArray = array();
                }

                // Finally, encode the array to JSON and output the results
                echo json_encode($resultArray);
            }

            // Close connections
            mysqli_close($result);
            mysqli_close($con);
        ?>

The trick seems to be there:

诀窍似乎在那里:

foreach ($row as $key => $value) {
                    $tempArray[$key] = iconv(mb_detect_encoding($value), 'UTF-8', $value);
}

In fact, since your values are probably not UTF-8 encoded, you can easily encode them correctly using the comfort iconv function (italian documentation: http://www.php.net/manual/it/function.iconv.php).

事实上,由于您的值可能不是UTF-8编码的,您可以使用comfort iconv函数轻松地对它们进行编码(意大利语文档:http://www.php.net/manual/it/function.iconv.php)。

From the example above, we are just getting the current encoding of the string and we're converting it to utf-8 regardless its current encoding.

从上面的示例中,我们只是获取字符串的当前编码,并将其转换为utf-8,而不考虑其当前编码。

Hope it helps!

希望它可以帮助!

Also, forgot to say that: utf8_encode was NOT working because utf8_encode expects the input string to be ISO-8859-1 encoded, while the above strings are ASCII.

另外,忘记说:utf8_encode不能工作,因为utf8_encode期望输入字符串是ISO-8859-1编码的,而上面的字符串是ASCII。

PHP警告:json_encode() [函数。json编码]:在参数中无效的UTF-8序列。

Moreover, you should also set, in PHP, the mysqli charset manually, perhaps all the problems you're having are related to this: http://php.net/manual/en/mysqli.set-charset.php

此外,您还应该在PHP中手动设置mymysqli字符集,可能您遇到的所有问题都与此相关:http://php.net/manual/en/mysqli.set-charset.php


Edit: right after connecting (after $con), try this:

编辑:连接后($con之后),试一下:

if (!mysqli_set_charset($con, "utf8")) {
    printf("Error loading character set utf8: %s\n", mysqli_error($link));
} else {
    printf("Current character set: %s\n", mysqli_character_set_name($link));
}

And, right after that, also write this:

然后,在那之后,也写下:

mb_internal_encoding("UTF-8");

Also, if you're echoing something, please be SURE that your HTML page as the charset defined as utf-8. In your <head> area, insert this:

此外,如果您正在重复某些内容,请确保您的HTML页面作为定义为utf-8的字符集。在您的区域,插入以下内容:

<meta charset="utf-8">

#2


0  

Coming late to the party. This is not supposed to be a complete answer, but it's an important info about the iconv() function of the approved answer: I had the same problem of the OP and I always got FALSE from iconv() function when my string contained at least 1 UTF-8 char, because there's an issue within a lib used by the iconv() function, as written here.

晚会来晚了。这不应该是一个完整的答案,但它是一个重要的信息的iconv()函数通过回答:我有OP的同样的问题,我总是从iconv()函数,当我得到了错误的字符串包含至少1 utf - 8字符,因为有一个问题在一个*使用iconv()函数,写在这里。

So, for me the solution was to very close to the accepted one, but using the mb_convert_encoding() function instead.

因此,对我来说,解决方案是非常接近可接受的方案,而使用mb_convert_encoding()函数。

#1


1  

From what we actually saw above, the solution should be something like this:

根据我们上面看到的,解决方案应该是这样的:

<?php

            // Create connection
            $con=mysqli_connect("mysql.example.com","example_example","password","example_exa");

            // Check connection
            if (mysqli_connect_errno())
            {
              echo "Failed to connect to MySQL: " . mysqli_connect_error();
            }

            // This SQL statement selects ALL from the table 'Locations'
            $sql = "SELECT * FROM Frasi";

            // Check if there are results
            if ($result = mysqli_query($con, $sql))
            {
                // If so, then create a results array and a temporary one
                // to hold the data
                $resultArray = array();
                $tempArray = array();

                // Loop through each row in the result set
                while($row = $result->fetch_object())
                {
                    // Add each row into our results array
                    foreach ($row as $key => $value) {
                        $tempArray[$key] = iconv(mb_detect_encoding($value), 'UTF-8', $value);
                    }
                    array_push($resultArray, $tempArray);
                    $tempArray = array();
                }

                // Finally, encode the array to JSON and output the results
                echo json_encode($resultArray);
            }

            // Close connections
            mysqli_close($result);
            mysqli_close($con);
        ?>

The trick seems to be there:

诀窍似乎在那里:

foreach ($row as $key => $value) {
                    $tempArray[$key] = iconv(mb_detect_encoding($value), 'UTF-8', $value);
}

In fact, since your values are probably not UTF-8 encoded, you can easily encode them correctly using the comfort iconv function (italian documentation: http://www.php.net/manual/it/function.iconv.php).

事实上,由于您的值可能不是UTF-8编码的,您可以使用comfort iconv函数轻松地对它们进行编码(意大利语文档:http://www.php.net/manual/it/function.iconv.php)。

From the example above, we are just getting the current encoding of the string and we're converting it to utf-8 regardless its current encoding.

从上面的示例中,我们只是获取字符串的当前编码,并将其转换为utf-8,而不考虑其当前编码。

Hope it helps!

希望它可以帮助!

Also, forgot to say that: utf8_encode was NOT working because utf8_encode expects the input string to be ISO-8859-1 encoded, while the above strings are ASCII.

另外,忘记说:utf8_encode不能工作,因为utf8_encode期望输入字符串是ISO-8859-1编码的,而上面的字符串是ASCII。

PHP警告:json_encode() [函数。json编码]:在参数中无效的UTF-8序列。

Moreover, you should also set, in PHP, the mysqli charset manually, perhaps all the problems you're having are related to this: http://php.net/manual/en/mysqli.set-charset.php

此外,您还应该在PHP中手动设置mymysqli字符集,可能您遇到的所有问题都与此相关:http://php.net/manual/en/mysqli.set-charset.php


Edit: right after connecting (after $con), try this:

编辑:连接后($con之后),试一下:

if (!mysqli_set_charset($con, "utf8")) {
    printf("Error loading character set utf8: %s\n", mysqli_error($link));
} else {
    printf("Current character set: %s\n", mysqli_character_set_name($link));
}

And, right after that, also write this:

然后,在那之后,也写下:

mb_internal_encoding("UTF-8");

Also, if you're echoing something, please be SURE that your HTML page as the charset defined as utf-8. In your <head> area, insert this:

此外,如果您正在重复某些内容,请确保您的HTML页面作为定义为utf-8的字符集。在您的区域,插入以下内容:

<meta charset="utf-8">

#2


0  

Coming late to the party. This is not supposed to be a complete answer, but it's an important info about the iconv() function of the approved answer: I had the same problem of the OP and I always got FALSE from iconv() function when my string contained at least 1 UTF-8 char, because there's an issue within a lib used by the iconv() function, as written here.

晚会来晚了。这不应该是一个完整的答案,但它是一个重要的信息的iconv()函数通过回答:我有OP的同样的问题,我总是从iconv()函数,当我得到了错误的字符串包含至少1 utf - 8字符,因为有一个问题在一个*使用iconv()函数,写在这里。

So, for me the solution was to very close to the accepted one, but using the mb_convert_encoding() function instead.

因此,对我来说,解决方案是非常接近可接受的方案,而使用mb_convert_encoding()函数。