我为客户端构建了一个插件,以便他们以CSV文件的形式下载数据.它已经设置好,当用户点击菜单中的链接时,CSV应该只是自动下载.但是,它不会像这样工作,只需将功能作为页面加载到wordpress后端.
function download_payment_csv() { include 'lib/connection.PHP'; $csv_output = ''; $values = $db->query('SELECT * FROM tbPayments ORDER BY date DESC'); $i=0; while ($rowr = MysqL_fetch_row($values)) { for ($j=0;$j<$i;$j++) { $csv_output .= $rowr[$j].","; } $csv_output .= "\n"; } header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate,post-check=0,pre-check=0"); header("Cache-Control: private",false); header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"report.csv\";" ); header("Content-Transfer-Encoding: binary"); echo $csv_output; }
正如我所说,它只是返回一个空白屏幕.任何帮助将不胜感激!
编辑
所以这是我现在正在使用的代码,从已经说过的代码中抽出来.
function download_payment_csv() { include 'lib/connection.PHP'; $csv_output = ''; $values = load_payment_csv(); $fp = fopen("PHP://output","w"); $file = 'test_export'; $filename = $file."_".date("Y-m-d_H-i",time()); header("Content-Type: text/csv"); header("Content-Disposition: attachment; filename=".$filename.".csv"); // Disable caching header("Cache-Control: no-cache,no-store,must-revalidate"); // HTTP 1.1 header("Pragma: no-cache"); // HTTP 1.0 header("Expires: 0"); // Proxies header("Content-Transfer-Encoding: UTF-8"); if(count($values) > 0) { foreach($values as $result) { fputcsv($fp,$result); } } fclose($fp); }
这会产生一个CSV,但是它有一个问题.问题是,当查看页面时,它不会将其下载为CSV,它只将CSV的内容输出到页面.但是,将此函数添加到插件的顶部:
add_action('admin_init','download_payment_csv');
/ **
*查询顶部行
* /
原文链接:https://www.f2er.com/php/139840.html*查询顶部行
* /
$results = $wpdb->get_results("SHOW COLUMNS FROM $table" ); if(count($results) > 0){ foreach($results as $result){ $csv_output .= str_replace('_',' ',$result->Field).","; //,or ; } } $csv_output .= "\n";
/ **
*查询所有必需的数据
* /
$results = $wpdb->get_results("SELECT * FROM $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"); print $csv_output; exit;
把这全部放在一个功能中应该做的伎俩