teelou teelou - 8 months ago 29
JSON Question

PHP encode_json - how to break each encoded row into a new line?

How can I break a new line on each json encoded row?

For instance,

header('Content-Type: application/json');

// Specify your sqlite database name and path //
$dir = 'sqlite:testDB.sqlite3';

// Instantiate PDO connection object and failure msg //
$dbh = new PDO($dir) or die("cannot open database");

// Define your SQL statement //
$query = "SELECT * FROM users";

// Iterate through the results and pass into JSON encoder //
foreach ($rows as $row) {
echo json_encode($row);

result (all rows in one line),

{"ID":"1","NAME":"Paul","AGE":"32","ADDRESS":"California","SALARY":"20000.0"}{"ID":"2","NAME":"Allen","AGE":"25","ADDRESS":"Texas","SALARY":"15000.0"}{"ID":"3","NAME":"Teddy","AGE":"23","ADDRESS":"Norway","SALARY":"20000.0"}{"ID":"4","NAME":"Mark","AGE":"25","ADDRESS":"Rich-Mond ","SALARY":"65000.0"}{"ID":"5","NAME":"David","AGE":"27","ADDRESS":"Texas","SALARY":"85000.0"}{"ID":"6","NAME":"Kim","AGE":"22","ADDRESS":"South-Hall","SALARY":"45000.0"}

But I am after (break every row into a new line),

{"ID":"4","NAME":"Mark","AGE":"25","ADDRESS":"Rich-Mond ","SALARY":"65000.0"}

Is it possible?


Depends on what you're trying to do. If you simply want to echo your JSON, just put a <br/> at the end of your echo.

Something like:

echo json_encode($row) . "<br/>";

Or just add a line break \n with double quotes.

echo json_encode($row) . "\n";

Or even, make it a paragraph with <p></p>

echo "<p>" . json_encode($row) . "</p>";