Export a mysql table into CSV using PHP code

前端 未结 4 1271
猫巷女王i
猫巷女王i 2021-01-20 22:56

I have a my sql table called pvdata, I would like to export it to csv file.

But I\'m obtaining the following results instead of the normal looking table:



        
4条回答
  •  感动是毒
    2021-01-20 23:17

    Try this code -

    ");
    
        // Fetch Record from Database
    
        $output = "";
        $table = ""; // Enter Your Table Name 
        $sql = mysql_query("select * from $table");
        $columns_total = mysql_num_fields($sql);
    
        // Get The Field Name
    
        for ($i = 0; $i < $columns_total; $i++) {
        $heading = mysql_field_name($sql, $i);
        $output .= '"'.$heading.'",';
        }
        $output .="\n";
    
        // Get Records from the table
    
        while ($row = mysql_fetch_array($sql)) {
        for ($i = 0; $i < $columns_total; $i++) {
        $output .='"'.$row["$i"].'",';
        }
        $output .="\n";
        }
    
        // Download the file
    
        $filename = time().'csv'; //For unique file name
        header('Content-type: application/csv');
        header('Content-Disposition: attachment; filename='.$filename);
    
        echo $output;
        exit;
    
        ?>
    

    Courtesy - Export MySQL table to CSV using PHP

提交回复
热议问题