Retrieve your database rows into an array and write the output of json_encode() to the output buffer with the appropriate header:
// Modify the fetch call for the MySQL API you're using:
// This is MySQLi...
$results = array();
while ($row = result->fetch_assoc()) {
// All results onto a single array
$results[] = $row;
}
// Supply header for JSON mime type
header("Content-type: application/json");
// Supply the Content-Disposition header if you want the browser
// to treat the file as a download and prompt to save it.
// Leave this out if that isn't what you want (I suspect it isn't)
header('Content-Disposition: attachment; filename="file.json"');
// Depending on how you want the JSON to look, you may wish to use
// JSON_FORCE_OBJECT
echo json_encode($results, JSON_FORCE_OBJECT);
From the browser's perspective, it is receiving a JSON file, though PHP is serving it.
If you actually need to save the JSON file rather than just output it, use file_put_contents()
file_put_contents('file.json', json_encode($results, JSON_FORCE_OBJECT));
// Read it back out with
echo file_get_contents('file.json');
// Or more simply
file('file.json');