PHP print_r有效,但json_encode返回空

前端之家收集整理的这篇文章主要介绍了PHP print_r有效,但json_encode返回空前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > json_encode is returning NULL?10个
我的PHP代码看起来像这样:
$header = "Content-Type: application/json";
header($header);

// Create connection
$conn = new MysqLi($servername,$username,$password,$dbname);

// Check connection
if ($conn->connect_error) {

    die("Connection Failed: " . $conn->connect_error);

} 

$sql = "SELECT * ...";

$result = $conn->query($sql);

$array_1 = array();

if ($result->num_rows > 0) {

    // output data as array
    while($row = $result->fetch_assoc()) {

        array_push($array_1,$row);

    }
}

$conn->close();

print_r($array_1);

这给了我以下的输出

Array
(
    [0] => Array
        (
            [user_email] => test@gmail.com
            [order_item_name] => Abonnement
        )

    [1] => Array
        (
            [user_email] => test@gmail.com
            [order_item_name] => Verlängerung
        )

)

输出是通过电子邮件查询的结果,以便返回产品的名称.在这种情况下,如果我用echo json_encode更改print_r则不会出现任何内容.这让我相信问题与字符集有关,因为结果不是空的,所以我补充说:

$header = "Content-Type: application/json; charset=utf-8";
header($header);

仍然没有运气.我一直在阅读可能是json *函数被禁用的情况,但是,如果我从查询中更改电子邮件,它将使用print_r显示结果,并使用echo json_encode完美地显示json.它必须来自此结果问题的根源,或任何类似的情况.可能是因为结果中的角色ä?这就是我在标题添加utf-8的原因.

正如我上面所说,如果我更改它的工作电子邮件,但当我使用“test@gmail.com”时它只显示1个结果而不是2.是不是结果没有正确放入数组?我相信没有给出print_r正确格式化查询结果.

有谁知道发生了什么?

json_encode仅支持UTF-8编码的字符串,因此您必须使用htmlentities或utf8_encode对order_item_name值进行编码
foreach($array1 as &$v) {
  $v['order_item_name'] = utf8_encode($v['order_item_name']);
}

print json_encode($array1);

有关详细信息,请参阅problems with german umlauts in php json_encode

原文链接:https://www.f2er.com/php/134114.html

猜你在找的PHP相关文章