Error in JSON with Accented Words

Asked

Viewed 64 times

0

I have a code in PHP, which prints values from the database in json.

<?php
    header('Content-Type: application/json; charset=utf-8');

    require_once "conexao.php";

    class Modelo {

      private $pdo;

      function Modelo() {
        $conexao = new Conexao();
        $this->pdo = $conexao->conect();
      }

      public function listaClientes() {

        $sql = "SELECT * from cliente";
        $sql = $this->pdo->query($sql);

        $lc = array();

        foreach($sql->fetchAll() as $cliente) {
          $lc[] = $cliente['nome'];
        }

        return json_encode($lc);
      }

    }

    $m = new Modelo();

    echo $m->listaClientes();

    echo json_last_error();

    ?>

It runs normal, but if I set some value with accent it shows nothing, just returns the value 5 of the function json_last_error, which in this case is an error with respect to UTF8

  • 5 = JSON_ERROR_UTF8: UTF-8 encoding error of JSON string;

inserir a descrição da imagem aqui

My bank already has the correct coding, how can I solve this problem?

  • Have you tried changing the application/json... for text/html?

  • Since it is a php file, I think MIME may be wrong.

  • @dvd switched to "text/html" but did not resolve. What would be MME?

  • MIME is the file type

  • Return json_encode($Lc, JSON_UNESCAPED_UNICODE);

  • I already put JSON_UNESCAPED_UNICODE, still giving the same error. @Guilherme

  • But the mysqli connection (in php) is also utf8? Something like mysqli_set_charset($conexao, "utf8")

  • I’m using PDO to make the connection @Juven_v

  • 1

    I hadn’t seen it. But the idea is the same. Here Soen has explaining how to configure with Pdo

  • That’s right @Juven_v, it worked here

Show 5 more comments
No answers

Browser other questions tagged

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