json_encode returns nothing

Asked

Viewed 2,951 times

3

What am I doing

I’m pulling data through PHP with a list of cities to create a chart with Javascript, and I realized that it was not returning the data, so I downloaded the file that takes the data from the database and does the conversion with the json_encode to see what would happen.

What happened

The method to get the cities is working, and when I give a print_r in the result it is shown correctly, but as soon as I give a echo json_encode($resultado) the page is empty.

My code

Calling Method and Parsing

$result = $cidadeDAO->getCidades();
echo json_encode($result);

Method to obtain cities

public function getCidades() {
        $stmt = self::$connection->prepare("SELECT cidade FROM cd_unidades order by cidade ASC");
        $stmt->execute();
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

Result print_r

Array
(
    [0] => Array
        (
            [cidade] => Araraquara
        )

    [1] => Array
        (
            [cidade] => Bauru
        )
)
  • There must be some mistake in the json_encode. Note in the manual that it returns FALSE if an error occurs.

  • Use the function json_last_error and verify which value is returned. In that reply there is an example with json_decode, just adapt it to json_encode.

3 answers

5

Check that the encodings are correct, use utf8_encode to convert and test:

$cidades = array();
while($row = $result->fetch()) {
{
   $cidade = array(
       'cidade' => utf8_encode($row['cidade']),
   );
   array_push($cidades, $cidade);
}
$json = json_encode($cidades);

If it works look in the PDO to open the connection already in UTF-8

$db = new PDO('mysql:host=myhost;dbname=mydb', 'login', 'password', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'')); 

Source: http://php.net/manual/en/pdo.construct.php

1


Try transforming his exit:

$cidades = array();
while($row = $result->fetch()) {
{
   $cidade = array(
       'cidade' => $row['cidade'],
   );
   array_push($cidades, $cidade);
}
$json = json_encode($cidades);

-1

Hello. I would like to share my solution. I am using Yii framework (MVC)

There in the model where you do the research I added the code:

 return CJSON::encode($this->findHardwareByCategoria(...));

And in the controller, after instantiating the model and storing the function result in a variable, I give a echo:

echo $minhaVariavel;
return true;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.