-1

I have json output written in php.

<?php
// parametri del database
$db_host = "<ip-address>";
$db_user = "<database user>";
$db_password = "<database password>";
$db_name = "<database name>";
$db = mysql_connect($db_host, $db_user, $db_password);
if ($db == FALSE)
die ("Errore nella connessione. Verificare i parametri..."); 
mysql_select_db($db_name, $db)
or die ("Errore nella selezione del database. Verificare i parametri...");
$q=mysql_query("SELECT * FROM <nome tabella>");
while($e=mysql_fetch_assoc($q))
        $output[]=$e;
print(json_encode($output));
mysql_close();
?>

The "problem" is that is not formatting well but the output is in a single line.

[{"id":"1","Nome":"Pippo","Cognome":"Paperino","mail":"pippo.paperino@disney.com","cell":"3333333333}]

How can i display the output like:

{
    "a": "apple",
    "b": "banana",
    "c": "catnip"
}

?

i tryied using echo json_encode($response, JSON_PRETTY_PRINT); but doesn't work.. i wrote

print(json_encode($output, JSON_PRETTY_PRINT)); but i get an error.

Atlas91
  • 5,754
  • 17
  • 69
  • 141
  • Update your PHP version. – BuysDB Jan 16 '14 at 12:01
  • First, you need to post the error in your question, second `JSON_PRETTY_PRINT` was only added in PHP 5.4 so you need to upgrade – Bojangles Jan 16 '14 at 12:01
  • It's first time i try to do something like this so maybe i wrong. Is there another way to formatting the json output instead using `JSON_PRETTY_PRINT`? – Atlas91 Jan 16 '14 at 12:04
  • Updated the php version but i display the same.. In one line.. I wrote: `echo json_encode($output, JSON_PRETTY_PRINT);` – Atlas91 Jan 16 '14 at 12:08
  • http://recursive-design.com/blog/2008/03/11/format-json-with-php/ – Jason Feb 13 '14 at 21:54

1 Answers1

0

First check with your json string its not a valid json. your json string should be:

[{"id":"1","Nome":"Pippo","Cognome":"Paperino","mail":"pippo.paperino@disney.com","cell":"3333333333"}]

You missed the double quote at the end in your json string.
You can check json is valid or not here

And why do you want formatted output?

user2936213
  • 1,021
  • 1
  • 8
  • 19
  • what i wrote is an example.. The data's aren't correct but invented because i can't write the right data output. Anyway i tryed to update the php version and i wrote: `echo json_encode($output, JSON_PRETTY_PRINT);` but doesn't work and it displays all in a single line again.. – Atlas91 Jan 16 '14 at 12:10
  • Ok. So for that Please see this link: http://stackoverflow.com/questions/2614862/how-can-i-beautify-json-programmatically – user2936213 Jan 16 '14 at 12:13