简体   繁体   中英

Creating JSON from PHP in a certain output format

I need to create a JSON file from a database using PHP, but the guys who will use the JSON file want it to be in a certain format. When I do it with json_encode, the output is like:

[{"pid":"76","language":"en","name":"Some name"},{"pid":"77","language":"en","name":"Some other name"}]

However, they want it like this:

{"pid":"76","language":"en","name":"Some name"}
{"pid":"77","language":"en","name":"Some other name"} 

So they don't want the "[" and "]" in the beginning and the end, they don't want "," between the {},{} and they want every {} in new lines.

Is this something I can do with PHP? Is there a way I can achieve this?

What you're being asked for is not valid JSON. However, each line is valid JSON, so if the file is read line by line, each line can be decoded.

All you need to do is loop through the array you're starting with and output each element, json_encoded, on a new line.

Something like this:

<?php
define("OUTFILE",'output.txt');

$arr = [["data1"=>"Some Data", "data2"=>"Some more data"],["data3"=>"Some Data", "data4"=>"Some more data"]];

if (file_exists(OUTFILE)) {
    unlink(OUTFILE);
}

foreach($arr as $obj) {
    file_put_contents(OUTFILE,  json_encode($obj)."\n", FILE_APPEND);
}

/* Output in file:
{"data1":"Some Data","data2":"Some more data"}
{"data3":"Some Data","data4":"Some more data"}
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM