Create a store procedure in mysql to create the data set as needed
Create a class in PHP to format Data Set in JSON as needed
Create a Control Form application (in scriptcase) to call SP, call function PHP to format data set, and send the file to client browser (download) in this way, if system has a security module, it's possible to manege who can download the result file.