WebDevDanno
WebDevDanno

Reputation: 1122

PHP to JSON encode data not working

I want to select all the recipes in my food database and encode them into a simple JSON response. I've looked at solutions around stack overflow and have implemented a sensible looking script.

No JSON array is returned / echoed.

Could someone tell me where I'm going wrong?

<?php
$type = "recipe";
$conn = mysqli_connect("localhost", "root", "", "food"); // SAMPLE CREDENTIALS
$sql = "SELECT * FROM wp_posts WHERE post_type = '$type' ";
$query = mysqli_query($conn, $sql);

$i = 0; // INCREMENT
$arr = [];

if($query) {
    while($row = mysqli_fetch_assoc($query)) {
        $jsonArrayObject = (array('title' => $row['post_title'] , 'excerpt' => $row['post_content']));
        $arr[$i] = $jsonArrayObject;
        $i++;
    }
    $json_array = json_encode($arr, JSON_PRETTY_PRINT);
    echo $json_array;
}
else {
    echo "Error in database";
}
?>

ARR VARIABLE PRINT OUT enter image description here

Upvotes: 0

Views: 38

Answers (1)

Andreas Schrammel
Andreas Schrammel

Reputation: 463

Check if your PHP version is 5.4.0 or above.

The option JSON_PRETTY_PRINT was introduced in that version according to http://php.net/manual/en/json.constants.php

If your PHP version is below 5.4.0 leave the option.

Upvotes: 1

Related Questions