Return Json with special characters

Asked

Viewed 578 times

1

I am performing a query in the database (Php, Mysql and Ajax), the return of this query is a Json, however all accents are coming with special characters, I put a log to see the result. Below contains the code that fills my array.

$sql = mysqli_query($conn,$query_somente_alunos_presentes);
$linhas=mysqli_num_rows($sql); 

if( $linhas > 0 ) {
    while($resultado = mysqli_fetch_assoc($sql)){
        $vetor[]= array_map('utf8_encode', $resultado); 
}    
    //Passando vetor em forma de json
    echo   json_encode($vetor);
} 

See log that comes out on the page:

Array(2)

0
:
{id: "1", nome: "Timóteo da Silva", imagem: "TimÃ_1520692755.jpg"}
1
:
{id: "10", nome: "João Barretos", imagem: "João_1520689587.jpg"}
2
:
{id: "11", nome: "João Pedro", imagem: "João_1520689891.jpg"}

I’ve tried using mysql set characters, utf8 all the way ....

  • the page is using meta chartset with utf8? The data saved in the bank is already utf8?

  • Yes the data is saved in utf-8 format and the page as well. <meta charset="utf-8">

  • then you do not need to convert, in "array_map('utf8_encode'", I believe

  • Like I do without the conversion?

  • 1

    @Paulogalego opens the file and saves it as utf-8, I’m sure that if, your bank and the file are in the same format will work

  • $vector[] =$result;

  • before that there is a step there, because it has a loop that every turn inserts the data of the variable $result inside the $vector[].

  • Julio, you mentioned that I must save the file in utf-8 format, I have here two php files, one to display the data and the other to process the information. which of these should I perform this save procedure as utf-8? And in save option as there is no utf8.... forgive my ignorance

  • got it!!! This really solved $vector[] =$result; Sveen!!!

  • The whole problem is that you must be coding something already encoded, you are basically programmed oriented to luck, with the forgiveness of the word. Understand that before creating something you must prepare the "whole environment" for the desired encoding, it is not because something is working that means it is correct, this answer explains everything: https://answall.com/a/43205/3635 - in short, you must configure the headers, bank and save everyone. php with the same encoding, if you leave something behind the problem may arise in the future.

Show 5 more comments

1 answer

0

I changed only one line of code:

if( $linhas > 0 ) {
    while($resultado = mysqli_fetch_assoc($sql)){
      //  $vetor[]= array_map('utf8_encode', $resultado); 
        $vetor[] =$resultado;  // <- apenas isso..
}    
    //Passando vetor em forma de json

    echo   json_encode($vetor);
} 

Browser other questions tagged

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