从MYSQL获取数据并显示在JSON文件中

时间:2012-05-20 21:46:41

标签: php mysql ios json

我正在构建和iOS应用程序从我的MYSQL数据库中获取数据,所以要做这样的事情我需要使用JSON(我知道其他方法,但我需要专门使用JSON)。问题是,如何从我的mysql数据库中获取数据并以JSON格式将其写入文件(最好使用PHP)。

非常感谢任何链接,教程或源代码!

3 个答案:

答案 0 :(得分:5)

将数据库行检索到数组中,并使用适当的标头将json_encode()的输出写入输出缓冲区:

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

从浏览器的角度来看,它正在接收一个JSON文件,尽管PHP正在提供它。

如果您确实需要保存 JSON文件而不是仅输出它,请使用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');

答案 1 :(得分:4)

只需使用json_encode

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

答案 2 :(得分:1)

  1. 从mysql获取数据并使用json_encode()

  2. 编码为json
  3. 使用fopen()fwrite()

  4. 写入文件
相关问题