簡體   English   中英

如何從 WordPress 插件中的函數下載 CSV 文件?

[英]How to download CSV file from function in WordPress plugin?

我為客戶端構建了一個插件,以便他們可以將數據下載為 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');

當單擊菜單鏈接時,這會觸發下載,這很好。 但是它會為插件中的每個菜單項觸發它,這是錯誤的。 它應該只在點擊下載鏈接時觸發。

/** * 查詢頂部標題行 */

$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"; 
    }
}

/** * 准備要導出的文件名和 CSV 文件 */

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

把這一切都放在一個函數中應該可以解決問題

嘗試這個:

<?php

class CSVExport
{
/**
 * Constructor
 */
public function __construct()
{
    if(isset($_GET['download_report']))
    {
        $csv = $this->generate_csv();

        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;
        exit;
    }

    // Add extra menu items for admins
    add_action('admin_menu', array($this, 'admin_menu'));

    // Create end-points
    add_filter('query_vars', array($this, 'query_vars'));
    add_action('parse_request', array($this, 'parse_request'));
}

/**
 * Add extra menu items for admins
 */
public function admin_menu()
{
    add_menu_page('Download Report', 'Download Report', 'manage_options', 'download_report', array($this, 'download_report'));
}

/**
 * Allow for custom query variables
 */
public function query_vars($query_vars)
{
    $query_vars[] = 'download_report';
    return $query_vars;
}

/**
 * Parse the request
 */
public function parse_request(&$wp)
{
    if(array_key_exists('download_report', $wp->query_vars))
    {
        $this->download_report();
        exit;
    }
}

/**
 * Download report
 */
public function download_report()
{
    echo '<div class="wrap">';
    echo '<div id="icon-tools" class="icon32"></div>';
    echo '<h2>Download Report</h2>';
    //$url = site_url();

    echo '<p><a href="site_url()/wp-admin/admin.php?page=download_report&download_report">Export the Subscribers</a>';
}

/**
 * Converting data to CSV
 */
public function generate_csv()
{
    $csv_output = '';
    $table = 'users';

    $result = mysql_query("SHOW COLUMNS FROM ".$table."");

    $i = 0;
    if (mysql_num_rows($result) > 0) {
        while ($row = mysql_fetch_assoc($result)) {
            $csv_output = $csv_output . $row['Field'].",";
            $i++;
        }
    }
    $csv_output .= "\n";

    $values = mysql_query("SELECT * FROM ".$table."");
    while ($rowr = mysql_fetch_row($values)) {
        for ($j=0;$j<$i;$j++) {
            $csv_output .= $rowr[$j].",";
        }
        $csv_output .= "\n";
    }

    return $csv_output;
}
}

// Instantiate a singleton of this plugin
$csvExport = new CSVExport();

您需要更改一些標題信息

header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename="report.csv"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0

之后使用 php://output 直接向瀏覽器提供數據,這將防止出現空白頁面。

例如:

$outstream = fopen("php://output", "w");

foreach($result as $result)
{
    fputcsv($outstream, $result);
}

fclose($outstream);
exit();

php://output 是一個只讀流,允許您直接向請求者提供數據。

編輯:你也應該使用 $wpdb

這是我找到的解決方案,當在網站的前端使用時,在輸出 HTML 代碼時遇到了很多麻煩。 關鍵是將退出交換為“死”。 這是我在自己的網站上使用的代碼。


header('Content-Type: text/csv');
$FileName = 'Content-Disposition: attachment; filename="'. 'Report.csv"';
header($FileName);

$fp = fopen('php://output', 'w');
    
$header_row = array(
        0 => 'data1',
        1 => 'data2',
        2 => 'data3',
    );
fputcsv($fp, $header_row); 

$rows = GetDataBaseData();
if(!empty($rows)) 
  {
   foreach($rows as $Record)
     {      
    // where data1, data2, data3 are the database column names 
    $OutputRecord = array($Record['data1'], $Record['data1'], $Record['data1']);
    fputcsv($fp, $OutputRecord);         
    }
    unset($rows);
  }

fclose( $fp );
    
die;   <===== key point.  Use DIE not Exit.  Exit will only work on the back end. Die will work on both.
```

Works on the front and backend of wordpress.    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM