Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Special characters with json in php

Tags:

json

php

mysql

I'm trying to get the data that is in the database and show them in json. But the words that have an accent are coming up like this: \ u00f3.

My code is like this: cidadeDao.php

<?php

class CidadeDAO {
    private $conexao;

    public function __construct() {
        $this->conexao = new Conexao();
    }

    public function consultarTodos() {

       // mysql_set_charset('utf8');
        $sql = "SELECT * FROM cidade";

        $resultado = mysqli_query($this->conexao->getCon(), $sql);

        return $resultado;
    }

}

?>

cidade.php

<?php

header("Content-Type: text/html; charset=UTF-8",true);

include '../Classes/Conexao.php';
include '../Classes/DAO/cidadeDao.php';

$cidadeDao = new cidadeDao();

$consulta = $cidadeDao->consultarTodos();

    for ($i = 0; $i < mysqli_num_rows($consulta); $i++){
        $linha = mysqli_fetch_array($consulta);

        $respostas [] = array (
            'id' => $linha['id'],
            'id_uf' => $linha['id_uf'],
            'cidade' => utf8_encode($linha['cidade'])
        );
    }

echo json_encode($respostas);
?>

When I check the json that is generated it looks like this:

[{"id":"1","id_uf":"1","cidade":"Sorocaba"},
{"id":"2","id_uf":"5","cidade":"Niter\u00f3i"},
{"id":"3","id_uf":"1","cidade":"Tatui"},
{"id":"4","id_uf":"1","cidade":"Itu"}]

Can anybody help me?

How can I handle words with accents and special characters in php?

like image 259
Lucas Santos Avatar asked Sep 02 '25 02:09

Lucas Santos


2 Answers

From the PHP Manual page on JSON Constants (you really should start there)

JSON_UNESCAPED_UNICODE

Encode multibyte Unicode characters literally (default is to escape as \uXXXX). Available since PHP 5.4.0.

so

json_encode('Niterói', JSON_UNESCAPED_UNICODE);

http://php.net/manual/en/function.json-encode.php

Edit: Also please see comments for reasons this approach can be problematic (it actually violates the RFC for JSON).

like image 182
MrMesees Avatar answered Sep 04 '25 22:09

MrMesees


  • You should use the mb_internal_encoding() function at the top of every file and the mb_http_output() function right after it .

  • Your database and tables that need to be set to the utf8mb4 character set and collation.

  • To save to database, use htmlentities and by precising UTF-8 like this htmlentities( $yourdata, ENT_QUOTES | ENT_HTML5, $encoding = 'UTF-8' );

and you must add this to access the database for mysqli :

$conn->set_charset('utf8mb4');
mysqli_set_charset($conn, 'utf8mb4');

Read here-- Working with UTF-8, FROM PHP the right way. http://www.phptherightway.com/#php_and_utf8

  • It explains how to use UTF-8 the right way at the PHP level, database level and the browser level.
like image 29
Michael GEDION Avatar answered Sep 04 '25 23:09

Michael GEDION