Why won’t json_encode encode this particular array but encodes other arrays with same structure?

I made an API that encodes data from a table to an array then to json.

 <?php
header('Content-type: application/json');
header("Access-Control-Allow-Origin: *");

...(connection to db)... :p

        $query = "SELECT * FROM gdb.".$_GET['table'];
        $result = mysqli_query($conn,$query);



$posts =array();

while ($row = mysqli_fetch_assoc($result))
{

    $posts[] = array('ONE'=>$row);




}

$all = array('ALL'=>$posts);
echo json_encode($all);//($posts);
mysqli_close($conn);
?>

it seems to work fine with other tables but with this particular table, json_encode doesn’t seem t work..

This is the array from the table it won’t encode to json:

array(1) {
  ["ALL"]=>
  array(61) {
    [0]=>
    array(1) {
      ["ONE"]=>
      array(12) {
        ["id_product"]=>
        string(1) "2"
        ["id_shop"]=>
        string(1) "1"
        ["id_lang"]=>
        string(1) "1"
        ["description"]=>
        string(72) "<p> BUY 5-KILOS  RICE FREE SARDINES 155G.SAVE 10.00</p>"
        ["description_short"]=>
        string(0) ""
        ["link_rewrite"]=>
        string(20) "5-kilos-rice"
        ["meta_description"]=>
        string(0) ""
        ["meta_keywords"]=>
        string(0) ""
        ["meta_title"]=>
        string(0) ""
        ["name"]=>
        string(40) "5-KILOS RICE FREE SARDINES"
        ["available_now"]=>
        string(0) ""
        ["available_later"]=>
        string(0) ""
      }
    }
    [1]=>
    array(1) {
      ["ONE"]=>
      array(12) {
        ["id_product"]=>
        string(1) "3"
        ["id_shop"]=>
        string(1) "1"
        ["id_lang"]=>
        string(1) "1"
        ["description"]=>
        string(78) "<p>BUY 10-KILOS RICE FREE SARDINES RED 155G.SAVE 20.00</p>"
        ["description_short"]=>
        string(0) ""
        ["link_rewrite"]=>
        string(21) "10-kilos-rice"
        ["meta_description"]=>
        string(0) ""
        ["meta_keywords"]=>
        string(0) ""
        ["meta_title"]=>
        string(0) ""
        ["name"]=>
        string(41) "10-KILOS RICE FREE SARDINES"
        ["available_now"]=>
        string(0) ""
        ["available_later"]=>
        string(0) ""
      }
    }
}}

The arrays from the ones that my code were able to encode to json have the same structure. Just different number of fields and content so I dunno why with this particular array, it wouldn’t work.

I figured. Maybe some of the description strings(did not include all in my sample) have quotes, doublequotes, slashes and that’s why it can’t encode to json so i did this in the while loop:

$posts[] =  array('ONE'=>array_map("addslashes",$row));

instead of this:

$posts[] = array('ONE'=>$row);

but it still doesn’t encode to json. Did i use array_map wrong?? or is there another reason why it won’t encode to json?


Source: json

Leave a Reply