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

时间:2015-03-01 20:02:30

标签: 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)) {
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")),
);

等等

if(!empty($json_data) && count($json_data) > 1)
{
$json_file_data = "";
$fp = fopen($json_file_name, 'w');
foreach($json_data as $row)
{
    $json_file_data .= implode(",", $row) . "\n";
}
fwrite($fp, $json_file_data);
fclose($fp);

实现同样目标的最佳途径是什么。

谢谢:)

2 个答案:

答案 0 :(得分:0)

如果您的数据库表不是太大,您可以将所有行提取到一个数组中,然后自动将该数组转换为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"]]

如果您的数据库表稍微大一点,最好在生成时编写每一行。下面的代码将为每一行创建一个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);

示例输出:

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

答案 1 :(得分:0)

我想你也想改变这一行:

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

到此:

$json_file_data[] = implode(",", $row);

这会导致这个:

$json = json_encode($json_data);

提供数据库行的json数组。