Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP print_r works, but json_encode returns empty [duplicate]

My php code looks like this:

$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 ouput:

Array
(
    [0] => Array
        (
            [user_email] => [email protected]
            [order_item_name] => Abonnement
        )

    [1] => Array
        (
            [user_email] => [email protected]
            [order_item_name] => Verlängerung
        )

)

This output is the result of a query by email, in order to return the name of the product. In this case, if I change print_r with echo json_encode nothing appears. This makes me believe that the problem has to do with the charset given that the result is not empty, so I added:

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

Still no luck. I have been reading that it may be the case that the json* functions are disabled, however, if I change the email from my query it displays the result as above using print_r and as json using echo json_encode perfectly fine. It must be from this result the root of the problem, or any similar scenario. Can it be because of the character ä from the result? Thats why I added utf-8 in the header.

As I said above, if I change the email it works, but it shows only 1 results instead 2 when I use "[email protected]". Can it be that the results are not put in the array correctly? I believe not given that print_r formats the query result correctly.

Does anyone know what is going on?

like image 552
Ava Barbilla Avatar asked Apr 30 '16 18:04

Ava Barbilla


1 Answers

json_encode only supports UTF-8 encoded strings, so you'll have 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 info see problems with german umlauts in php json_encode

like image 115
FuzzyTree Avatar answered Oct 25 '22 01:10

FuzzyTree