PHP print_r works, but json_encode returns empty

My PHP code is as follows:

$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); 

Which gives me the following conclusion:

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

This result is the result of an email request to return the product name. In this case, if I change print_r to echo json_encode , nothing appears. This leads me to believe that the problem is with the encoding, given that the result is not empty, so I added:

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

Still out of luck. I read that it may be that the json * functions are disabled, however, if I change the email address from my request, it will display the result as above using print_r and like json using echo json_encode perfectly. From this result there must be the root of the problem or any similar scenario. Could this be due to the ä symbol from the result? This is why I added utf-8 to the header.

As I said above, if I change the email address, it works, but it shows only 1 result instead of 2 when I use " test@gmail.com ". Maybe the results do not fit into the array correctly? I believe that it is not indicated that print_r correctly formats the result of the request.

Does anyone know what is going on?

+6
source share
1 answer

json_encode only supports UTF-8 encoded strings, so you will need to encode your order_item_name values ​​using either htmlentities or utf8_encode

 foreach($array1 as &$v) { $v['order_item_name'] = utf8_encode($v['order_item_name']); } print json_encode($array1); 

For more details see problems with German umlauts in php json_encode

+5
source

All Articles