Mateus
Mateus

Reputation: 2668

Fetch data from MYSQL and display in JSON file

I'm building and iOS application which fetches data from my MYSQL database, so to do such thing i need to use JSON (i know other methods,but i need specifically to use JSON). The problem is, how can i fetch data from my mysql database and write it to file in JSON format (preferably using PHP).

Any link,tutorial or source code will be much appreciated!

Upvotes: 2

Views: 4912

Answers (3)

Michael Berkowski
Michael Berkowski

Reputation: 270609

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');

Upvotes: 5

ilanco
ilanco

Reputation: 9957

  1. fetch data from mysql and encode to json with json_encode()

  2. write to a file with fopen() and fwrite()

Upvotes: 1

AD7six
AD7six

Reputation: 66169

Just use json_encode

... code that builds an array from any source you like
header('Content-type: application/json');
echo json_encode($anArray);
die;

Upvotes: 4

Related Questions