How to return a JSON in PHP?

Asked

Viewed 2,566 times

-1

I have it:

$insereUsuario=$pdo->prepare("INSERT INTO usuarios (idUsuario, idCep, tipoUsuario, nome, usuario, email, senha) VALUES (?, ?, ?, ?, ?, ?, ?)");
$insereUsuario->bindValue(1, NULL); 
$insereUsuario->bindValue(2, $idCep); 
$insereUsuario->bindValue(3, $tipoUsuario); 
$insereUsuario->bindValue(4, $nome);
$insereUsuario->bindValue(5, $usuario);
$insereUsuario->bindValue(6, $email);
$insereUsuario->bindValue(7, $senha);
$insereUsuario->execute();

$idUsuario = $pdo->lastInsertId();

//$data = array();

$result = array(
   'email' => $email,
   'nome' => $nome,
   'usuario' => $usuario,
   'idUsuario' => $idUsuario,
   'tipoUsuario' => $tipoUsuario
  );

//$data[] = $result;
print_r($result);

I’m trying to get this JSON Object at the angle, and on the console appears this: "Array n( n [email] => [email protected] n [name] => Fl via Schneider n [user] => Fl via n [idUsuario] => 33 n [typeUsuario] => C n) n"

How do we fix this? Thanks.

  • $result = array( 'email' => $email, 'name' => $name, 'user' => $user, 'idUsuario' => $idUsuario, 'userUsuario' => $userUsuario ); echo json_encode($result);

2 answers

1

You need to add the header for the browser to recognize the format, then serialize the json object:

header('Content-Type: application/json');
echo json_encode($result);

1

Might turn:

$result['email'] = '$email';
$result['nome'] = '$nome';
echo json_encode($result);

Browser other questions tagged

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