drnf593779 2015-03-01 12:02
浏览 99
已采纳

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

So I want to export a JSON file from a MySQL database table, a php script that runs weekly and exports JSON file from a specific table.

This is sort of the thing I want to achieve:

  <?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")),
);

and so on

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) . "
";
}
fwrite($fp, $json_file_data);
fclose($fp);

What is the best way to achieve the same.

Thank you :)

展开全部

  • 写回答

2条回答 默认 最新

  • dou7851 2015-03-01 12:08
    关注

    If your database table not too large, you can fetch all rows into a single array, then turn that array into JSON automatically without looping. This will generate JSON with column values as a list:

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

    Example output:

    [["name1","address1"],["name2","address2"]]
    

    If your database table is a little bigger, it is better to write each line as it is generated. The code below will create a JSON object for each row.

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

    Example output:

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

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部