2015-08-14 13 views
12

Tôi đã tạo plugin cho khách hàng để họ có thể tải xuống dữ liệu dưới dạng tệp CSV. Nó được thiết lập để khi người dùng nhấp vào một liên kết trong menu, CSV sẽ chỉ tự động tải xuống. Tuy nhiên, nó không hoàn toàn hoạt động như thế và chỉ tải chức năng như một trang trong phần phụ trợ WordPress.Cách tải xuống tệp CSV từ chức năng trong plugin WordPress?

Đây là mã tôi đã cho các chức năng:

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; 

} 

Và như tôi đã nói, nó chỉ trả về một màn hình trống. Bất kỳ trợ giúp sẽ được đánh giá cao!

EDIT Vì vậy, đây là mã tôi hiện đang làm việc, lấy bit từ những gì đã được nói.

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

} 

Điều này tạo ra CSV, nhưng có vấn đề với vấn đề này. Khi xem trang không tải xuống dưới dạng CSV, nó chỉ xuất nội dung của CSV vào trang . Tuy nhiên, thêm chức năng này vào đầu plugin:

add_action('admin_init','download_payment_csv'); 

Điều này sau đó kích hoạt tải xuống khi liên kết menu được nhấp vào. Nhưng nó kích hoạt nó cho mọi mục menu trong plugin, điều đó là sai. Nó chỉ nên kích hoạt khi liên kết tải xuống được nhấp.

+0

nếu bạn chỉ vang '$ csv_output'; bạn có nhận được kết quả nào không? –

+0

Khi nó tải chỉ là chức năng, nó có chứa bất kỳ đầu ra nào không?Ngoài ra ** không sử dụng mysql_, sử dụng PDO hoặc mysqli _ ** – Justinas

+0

Tôi nhận được hoàn toàn không có đầu ra khi chỉ echo'ing $ csv_output khi nó được tải như chỉ là chức năng – mickburkejnr

Trả lời

2

Bạn sẽ cần phải thay đổi một số thông tin tiêu đề

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 

Sau đó tận dụng php: // sản lượng để cung cấp dữ liệu trực tiếp vào trình duyệt, điều này sẽ ngăn chặn các trang trống.

ví dụ:

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

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

fclose($outstream); 
exit(); 

php: // đầu ra là một dòng suối đọc duy nhất cho phép bạn cung cấp dữ liệu trực tiếp cho người yêu cầu.

EDIT: Ngoài ra, bạn nên tận dụng $ wpdb

7

Hãy thử điều này:

<?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(); 
+3

Vấn đề bảo mật khá lớn ở đây ... bất cứ ai cũng có thể tải xuống báo cáo bằng cách đoán tham số 'download_report'. – Mikk3lRo

12

/** * Query Ví Lên trên Tiêu đề Row */

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

/* * * Truy vấn cho tất cả các dữ liệu bắt buộc */

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

/** * Chuẩn bị tên tập tin và CSV File để xuất khẩu */

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

Đưa tất cả điều này trong một chức năng nên làm các trick

+2

Đây là dude tuyệt vời :) –

+1

Điều này là tốt, nhưng tôi nhận được lỗi nói rằng thông tin tiêu đề không thể sửa đổi? – mickburkejnr

Các vấn đề liên quan