My json returns invalid character in PHP

0

I need to mount a JSON , in PHP , to return data to AngularJS, but one of the JSON object's data is coming with the letter "á" with another character. How can I fix this? NOTE: The name is accented in the BD, because it was inserted in the DB with an accent. DB is configured with utf8-bin.

My php:

<?php
ini_set('display_errors', true);
error_reporting(E_ALL);

header('Access-Control-Allow-Origin: *');
header('Content-Type: text/html; charset=utf-8');

include_once("conPDO.php");
$pdo = conectar();

$idUsuario = $_GET['idUsuario'];

$pegaUsuario=$pdo->prepare("SELECT * FROM usuarios WHERE idUsuario=:idUsuario");
$pegaUsuario->bindValue(":idUsuario", $idUsuario);
$pegaUsuario->execute();

$return = array();

while ($linha=$pegaUsuario->fetch(PDO::FETCH_ASSOC)) {
    array_push($return, $linha);
}
print_r($return[0]);
//echo json_encode($return[0]);

? >

And see how object json appears on the console, see the name.

    
asked by anonymous 24.06.2016 / 04:56

3 answers

1

Another solution, if the aforementioned does not work, is to go through the object that turns its attributes into UTF8 :

for(x in objeto){
  objeto[x] = utf8_encode(objeto[x]);
}

Edited

Solution:

while ($linha=$pegaUsuario->fetch(PDO::FETCH_ASSOC)) {
    $linha['nome'] = utf8_encode($linha['nome']); 
    array_push($return, $linha);
}
    
24.06.2016 / 13:47
0

You can use various php functions to convert your character into an html character, ansii etc use this function before saving to the database

htmlentities($suaString) 

this will convert your character to a character &aacute; There are several factors that may be causing this charcode error check if your file is in utf-8 recommend this formatting, if there is an include of another make sure it is also formatted use the meta tag <meta charset="utf-8"> in html also use the header in php

header('Content-Type: text/html; charset=utf-8')

Resume working with notpad ++ you can download it here

    
24.06.2016 / 05:43
0

As another alternative, and by narrowing down some lines of code, use fetchAll for now get array containing elements of rows returned in sql and function array_map to apply utf8_encode on all elements of array :

$return = $pegaUsuario->fetchAll(PDO::FETCH_ASSOC);
$encoded = array_map("utf8_encode", $return);

var_dump(json_encode($encoded, JSON_UNESCAPED_UNICODE));
    
24.06.2016 / 16:44