Json output with json_encode()

Asked

Viewed 1,792 times

5

json_encode() - Returns the JSON representation of a value

If I do:

$foo = array('a', 'b', 'c', 'd', 'e');
echo json_encode($foo);

I’ll get:

["a","b","c","d","e"]

So far so good, I’m taking an array and turning it into a json object.

Now if I try to make a query and return a multidimensional array to turn into json it doesn’t work.

Example:

include '../db/pdo.php';
$sql = $pdo->prepare('SELECT  * FROM CLIENTES WHERE ID > 0');
$sql->execute();
$result = $sql->fetchAll();
echo json_encode($result);

What am I forgetting ? Both are picking up an array and turning into JSON.

Array output:

array (size=2)
  0 => 
    array (size=22)
      'CODIGO' => string '1' (length=1)
      'NOME' => string 'MARIA DA SILVA' (length=14)
      'TIPOPESSOA' => string 'F' (length=1)
      'CPF' => string '12345678912' (length=11)
      'CGC' => null
      'CONTACORRENTE' => null
      'REGIAO' => null
      'ENDERECO' => null
      'NUMERO' => null
      'SETOR' => null
      'CIDADE' => null
      'UF' => null
      'CEP' => null
      'FONE' => null
      'FAXCEL' => null
      'ENDENDERECO_1' => null
      'NUMERO_1' => null
      'SETOR_1' => null
      'CIDADE_1' => null
      'UF_1' => null
      'CEP_1' => null
      'FONE_1' => null
  1 => 
    array (size=22)
      'CODIGO' => string '2' (length=1)
      'NOME' => string 'SU�LLEM DA SILVA' (length=24)
      'TIPOPESSOA' => string 'F' (length=1)
      'CPF' => string '12345678912' (length=11)
      'CGC' => null
      'CONTACORRENTE' => null
      'REGIAO' => null
      'ENDERECO' => string 'ENDERECO' (length=19)
      'NUMERO' => string '401' (length=3)
      'SETOR' => string 'SETOR' (length=8)
      'CIDADE' => string 'BUENO' (length=13)
      'UF' => string 'RO' (length=2)
      'CEP' => string '12345678912' (length=8)
      'FONE' => string '12345678912' (length=10)
      'FAXCEL' => null
      'ENDENDERECO_1' => null
      'NUMERO_1' => null
      'SETOR_1' => null
      'CIDADE_1' => null
      'UF_1' => null
      'CEP_1' => null
      'FONE_1' => null

Using json_last_error() get back to me 5 = JSON_ERROR_UTF8.

2 answers

2


To solve the coding problem I went through the array by creating a new one and using utf8_encode() to leave everything with utf-8.

$novo = array();
foreach ($result as $key => $value) {
   foreach ($value as $k => $v) {
     $novo[$key][$k] = utf8_encode($v);
   }
}

echo json_encode($novo);
  • It is not a suitable solution. It apparently solves but it is a gambiarra. You should try to solve the problem at the root. I think the data is being recorded with a different I found than the database is configured.

  • @Danielomine I agree with you, this solution is the same of a library called adodb, it seems to me a gambiarra and spend time redoing the array, I created this topic to try to centralize the problem of the bank charset http://answall.com/q/97469/17658

  • 1

    bad example about adodb.. rsrs.. but I got the point.. I saw the link with the question about setting the charset in Firebird.. But I guess you still don’t understand that the hole is further down. I suspect the problem lies in the way you save the data, as I described in the comment above. Look in the script that makes the Insert. But it can also diagnose at the time of select using mb_detect_encoding(). I point out that it is a suspect, but it is the first test I would do to find the problem.

  • @Danielomine para você ter ideia esse banco é utilizado em uma aplicação Delphi e em uma web, I just went through a change from adodb to Pdo because of the best performance presented in Pdo and now I’m having these problems with charset

  • @Danielomine if in Delphi they can save the data and get it encoded I should do too, you think the problem is in the database or in the configuration of Pdo ?

  • 1

    puts... that’s what I mentioned three times above.. about talking about the relevant details.. This about the bank being used by another application in a totally different language, it changes the course of things a lot.. but it is more certain that the problem may be at the moment that the data is saved. It may be being saved in an Encounter other than UTF8.. understood ? you need to find out how the app in Delphi is saving, what the charset of that app is. It shouldn’t be hard.. probably using windows-1252, ISO8859-1 or something.

Show 1 more comment

2

As an alternative you can use SET names mysql:

$dbh = new PDO(...);
$dbh->exec('SET names utf8');

Being Firebird (I couldn’t test):

$str_conn = 'firebird:host=localhost;dbname=/var/lib/firebird/2.5/data/employee.fdb;charset=UTF8';
$dbh = new PDO($str_conn, 'sysdba', 'senha');

Just in case, an alternative to your answer would be to use the array_map

$result = array_map('utf8_encode', $result);

Or array_walk_recursive for cases where there are multidimensional arrays:

function encode_items(&$item, $key)
{
    $item = utf8_encode($item);
}

array_walk_recursive($jobs, 'encode_items');

Source: https://stackoverflow.com/a/3913024/1518921

  • No doubt your answer would be ideal if I was using mysql, but use Firebird, I’m trying to solve this big puzzle here:http://answall.com/q/97469/17658 can help me ?

  • I understood @Gabrielrodrigues so I always recommend you to follow http://answall.com/help/mcve, because this always helps to formulate more definitive answers, see I updated the answer, I could not test.

  • I did a benchmack comparing the array_walk_recursive + função vs 2 foreach, foreach are 46% faster. I will read this article, thank you.

  • @Gabrielrodrigues Excellent!! Then tell me the array_map, note that the array_walk_recursive is mostly used for multidimensional and so should slow down.

  • The performance of the array_map is very similar to that of the array_walk_recursive, both functions solved the problem using a multidimensional array, has some peculiarity of walk_recursive for it to be used more ?

  • @Gabrielrodrigues yes it is used with multi-dimensional arrays, which is not your current case :) - A question ;charset=UTF8'; didn’t work?

  • No, this was my first test :(

Show 2 more comments

Browser other questions tagged

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