What happens is that JSON expects a array
and you send it a string, test in your loop that it is a array
instead of a string and that way it will be possible to convert it to a JSON format.
<?php
...
$sql = $conn->prepare('SELECT titulo FROM noticias');
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_OBJ)) {
$data['titulo'][] = $row->titulo;
}
echo json_encode($data);
exit();
?>
To provide a better context related to the use of indexed arrays or anonymous objects, a related example follows:
// FETCH_ASSOC -- Arreglo indexado ver ref. bibliografica
$stmt = $dbh->prepare("SELECT titulo FROM noticias");
// Especificamos el fetch mode antes de llamar a fetch()
$stmt->setFetchMode(PDO::FETCH_ASSOC);
// Ejecutamos
$stmt->execute();
// Mostramos los resultados
while ($row = $stmt->fetch()){
echo "Nombre: {$row["titulo"]} <br>";
}
// FETCH_OBJ -- Objeto anónimo ver Ref. bibliografica
$stmt = $dbh->prepare("SELECT titulo FROM noticias");
// Ejecutamos
$stmt->execute();
// Ahora vamos a indicar el fetch mode cuando llamamos a fetch:
while($row = $stmt->fetch(PDO::FETCH_OBJ)){
echo "Nombre: " . $row->titulo . "<br>";
}
Bibliography: link
I hope you find it useful.