json_encode() — Retorna a representação JSON de um valor
Se eu fizer:
$foo = array('a', 'b', 'c', 'd', 'e');
echo json_encode($foo);
Vou conseguir:
["a","b","c","d","e"]
Até ai tudo bem, estou pegando um array e transformando em um objeto json.
Agora se eu tento fazer uma consulta e retornar um array multidimensional para transformar em json não funciona.
Exemplo:
include '../db/pdo.php';
$sql = $pdo->prepare('SELECT * FROM CLIENTES WHERE ID > 0');
$sql->execute();
$result = $sql->fetchAll();
echo json_encode($result);
O que estou esquecendo ? Ambos estão pegando um array e transformando em JSON.
Saída do array:
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
Usando json_last_error()
me retorna 5 = JSON_ERROR_UTF8
.