PHP encode_json - 如何将每个编码行分成新行?

时间:2015-08-10 04:11:56

标签: php json php-5.6

如何在每个JSON编码的行上打破一个新行?

例如,

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) {
    //var_dump($row);
    echo json_encode($row);
}

结果(一行中的所有行),

{"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"}

但我追求(将每一行分成一个新行),

{"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"}

有可能吗?

1 个答案:

答案 0 :(得分:3)

取决于您尝试做什么。如果您只想{J}个{J},只需在echo的末尾添加<br/>

类似的东西:

echo

或者只使用双引号添加换行符echo json_encode($row) . "<br/>";

\n

甚至可以将其设为echo json_encode($row) . "\n";

的段落
<p></p>