Home >Backend Development >PHP Tutorial >How to quickly export database to csv in php (code implementation)

How to quickly export database to csv in php (code implementation)

不言
不言Original
2018-08-29 16:35:542559browse

The content of this article is about how to quickly export database to csv in PHP (code implementation). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Requirements

You need to export all the databases to the local through the download button on the browser page.

Proposal

Every time a row of database records is read, echo one row to the output;

Implementation

//导出函数,参数$mycli已打开数据库的mycli对象
function exportDbTable($mysqi){
    //首先输出头部
    header("Content-type:text/csv;");
    header("Content-Disposition:attachment;filename=" . "FixedAssets.csv");
    header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
    header('Expires:0');
    header('Pragma:public');    
    $tbName = '表名';    
    $output = fopen('php://output', 'w');  //打开输出

    //先获取一行,以便生成csv的首行, 列名
    $sql="select * from {$tbName} limit 1";    
    $res = $mysqli->query($sql);    
    if(!$res)        
    return;  //错误处理
    $row = $res->fetch_assoc()
    fputcsv($output, array_keys($row));  //输出csv头部

    //导出表数据
    $sql="select * from {$tbName}";  //导出表内容
    $res = $mysqli->query($sql);    
    while ($row = $res->fetch_assoc())
        fputcsv($output, $row);
    fclose($output);
}

Related recommendations:

Detailed explanation of PHP How to export the database to a csv file

How to export data to CSV with PHP

The above is the detailed content of How to quickly export database to csv in php (code implementation). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn