json_encode - Invalid JSON

4

I created a PHP code to fetch information from a database (MySQL) and "transform" into JSON. I used json_encode to do this.

The output JSON seemed to be correct, but when I use some JSON validator, it always returns a Unexpected token error.

What puzzles me most is that if I manually enter the output JSON in the validator, it works! If I give Ctrl + C and Ctrl + V, the error occurs.

To check the JSON result: link

What can it be?

<?php
include('connectdb.php');

$something = $_GET['cod'];
$sqlcode = mysql_query("Select descricao from Produtos Where codigo='$something'");
$sqlcode2 = mysql_query("Select descricao from Produtos");

$jsonObj = array();

if ($something == 'all') {
    while ($result = mysql_fetch_object($sqlcode2)) {
        $jsonObj[] = $result;
    }
} else {
    while ($result = mysql_fetch_object($sqlcode)) {
        $jsonObj[] = $result;
    }
}

$final_res = json_encode($jsonObj);

echo $final_res;
?>
    
asked by anonymous 14.10.2014 / 15:28

1 answer

7

A likely diagnosis may be the type of encoding.

To correct this, enter the file type header, leave no character type before and after the output, ensure that your <?php tag is the first thing in the file, and remove the ?> tag from the end of the file. file, or add a exit; :

header('Content-Type: application/json');
$final_res = json_encode($jsonObj);
echo $final_res;
exit;

Check the encoding of your database, the PHP file that is printing the data, and the file that is receiving the data. If possible put all in UTF-8 without BOM English .

Complement :

NotethattherearetwofileswithBOMatthebeginning.

Thecodeforphpheader:

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