Php 从MYSQL获取数据并显示在JSON文件中
我正在构建一个iOS应用程序,它从我的MYSQL数据库中获取数据,所以要做这样的事情,我需要使用JSON(我知道其他方法,但我需要特别使用JSON)。问题是,如何从mysql数据库中获取数据,并将其以JSON格式写入文件(最好使用PHP) 任何链接,教程或源代码将不胜感激 只要使用Php 从MYSQL获取数据并显示在JSON文件中,php,mysql,ios,json,Php,Mysql,Ios,Json,我正在构建一个iOS应用程序,它从我的MYSQL数据库中获取数据,所以要做这样的事情,我需要使用JSON(我知道其他方法,但我需要特别使用JSON)。问题是,如何从mysql数据库中获取数据,并将其以JSON格式写入文件(最好使用PHP) 任何链接,教程或源代码将不胜感激 只要使用 将数据库行检索到一个数组中,并将json_encode()的输出写入具有适当标头的输出缓冲区: // Modify the fetch call for the MySQL API you're using: //
将数据库行检索到一个数组中,并将
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\u put\u contents()
json\u encode()编码为json
fopen()
和fwrite()写入文件
JSON文件??我想你的意思是将MySQL存储在一个JSON对象中(比如JSON数组)?是的,你说得对,我会修复它@Mateunune在两个示例中都将
echo
输出,或者file()
从磁盘读取并一次性将其输出到浏览器。
// 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);
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');