2

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!

2
  • JSON file?? I assume you mean store the resutling MySQL in a JSON Object (like a JSON array) ? Commented May 20, 2012 at 21:47
  • Yes,you're right,i'll fix it! Commented May 20, 2012 at 21:50

3 Answers 3

5

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');
Sign up to request clarification or add additional context in comments.

1 Comment

@MateusNunes The echo outputs it in both examples, or file() reads from disk and outputs it to the browser in one go.
4

Just use json_encode

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

Comments

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.