Php 如何从MySQL数据库实时/动态生成JSON

Php 如何从MySQL数据库实时/动态生成JSON,php,mysql,json,Php,Mysql,Json,所以我想从MySQL数据库表导出一个JSON文件,这是一个php脚本,每周运行一次,并从特定表导出JSON文件 这就是我想要实现的目标: <?php $json_file_name = "File_export.json"; $json_file_name = str_replace(" ", "_", $json_file_name); $con = mysqli_connect("", "", "", ""); if (mysqli_connect_errno($con))

所以我想从MySQL数据库表导出一个JSON文件,这是一个php脚本,每周运行一次,并从特定表导出JSON文件

这就是我想要实现的目标:

  <?php

$json_file_name = "File_export.json";
$json_file_name = str_replace(" ", "_", $json_file_name);

$con = mysqli_connect("", "", "", "");

if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$date_range = array(
    "start" => date("Y-m-d H:i:s", strtotime("-7 days")),
    "end" => date("Y-m-d H:i:s", strtotime("now")),
);
实现同样目标的最佳方式是什么


谢谢:)

如果您的数据库表不太大,您可以将所有行提取到单个数组中,然后将该数组自动转换为JSON,而无需循环。这将生成列值为列表的JSON:

// $con is connection, $json_filename is name of filename to write
$query = "select * from MyTable";

// Fetch all rows into $json_data array
$result    = mysqli_query($con, $query);
$json_data = mysqli_fetch_all($result);
mysqli_close($con);

// Turn data into JSON and write to file
$json = json_encode($json_data);
file_put_contents($json_filename, $json);
示例输出:

[["name1","address1"],["name2","address2"]]
[{"name": "name1", "address": "address1"},{"name": "name2", "address": "address2"}]
如果数据库表稍微大一点,最好在生成每一行时写入它。下面的代码将为每一行创建一个JSON对象

$query  = "select * from MyTable";
$result = mysqli_query($con, $query);

// Open output file
$fp = fopen($json_file_name, 'w');

// Write JSON list start    
fwrite($fp, '[');

// Write each object as a row
$isFirstRow = true;
while ($row = mysqli_fetch_assoc($result)) {
    if (!$isFirstRow) {
        fwrite($fp, ',');
    } else {
        $isFirstRow = false;
    }
    fwrite($fp, json_encode($row));
}

// Write JSON list end
fwrite($fp, ']');

// Close file and MySQL connection
fclose($fp);
mysqli_close($con);
示例输出:

[["name1","address1"],["name2","address2"]]
[{"name": "name1", "address": "address1"},{"name": "name2", "address": "address2"}]

我想你也想改变这一行:

$json_file_data .= implode(",", $row) . "\n";
为此:

$json_file_data[] = implode(",", $row);
这将导致:

$json = json_encode($json_data);

提供数据库行的json数组。

干杯,我的表确实不是“太大”,所以上面的应该可以!谢谢