gpt4 book ai didi

php - Wordpress - 将 mysql 表导出到带有列标题的 csv

转载 作者:行者123 更新时间:2023-11-30 21:57:03 25 4
gpt4 key购买 nike

我可以为我的表格下载一个 csv 格式的文件,但如何将列标题添加到同一文件。

当前代码如下-

// load wpdb
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';

global $wpdb;

$table = $_POST["table_name"];// table name
$file = 'database_csv'; // csv file name
$results = $wpdb->get_results("SELECT * FROM $wpdb->prefix$table",ARRAY_A );

if(count($results) > 0){
foreach($results as $result){
$result = array_values($result);
$result = implode(", ", $result);
$csv_output .= $result."\n";
}
}

$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
header("Pragma: no-cache");
header("Expires: 0");
print $csv_output;
exit;

最佳答案

我能够通过首先获取列名然后将其分配给最终输出来做到这一点:

  $table_name = $wpdb->prefix.$_POST["table_name"];// table name
$file = 'database_csv'; // csv file name
$results = $wpdb->get_results("SELECT * FROM $table_name",ARRAY_A );

// get column names
$query = "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='".$wpdb->dbname."' AND `TABLE_NAME`='".$table_name."'";

$columnNamesList = $wpdb->get_results($query);


foreach ( $columnNamesList as $column_name ) {
$csv_output.=$column_name->COLUMN_NAME.",";
}


// remove last additional comma
$csv_output = substr($csv_output,0,strlen($csv_output)-1);

// start dumping csv rows in new line
$csv_output.="\n";

if(count($results) > 0){
foreach($results as $result){
$result = array_values($result);
$result = implode(", ", $result);
$csv_output .= $result."\n";
}
}

$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
header("Pragma: no-cache");
header("Expires: 0");
print $csv_output;
exit;

关于php - Wordpress - 将 mysql 表导出到带有列标题的 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44804334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com