2014-02-05 34 views
0

我無法制作一個.csv文件,並強制其在wordpress插件下載。wordpress插件中的強制文件下載

如果我在php插件中調用這段代碼,我得到「無法修改標題」,並且我從外部wordpress調用我,我可以下載.csv,但不能包含wpdb.php(有意思的是因爲我不'無法訪問我的插件文件夾外)

<?php 
$fileName = 'somefile.csv'; 

header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header('Content-Description: File Transfer'); 
header("Content-type: text/csv"); 
header("Content-Disposition: attachment; filename={$fileName}"); 
header("Expires: 0"); 
header("Pragma: public"); 

$fh = @fopen('php://output', 'w'); 

global $wpdb; 
$query = "SELECT nome, email FROM {$wpdb->prefix}coming_soon_lista_email"; 
$results = $wpdb->get_results($query, ARRAY_A); 
$headerDisplayed = false; 

foreach ($results as $data) { 
    if (!$headerDisplayed) { 
     fputcsv($fh, array_keys($data)); 
     $headerDisplayed = true; 
    } 
    fputcsv($fh, $data); 
} 
fclose($fh); 
exit; 
?> 

這種情況下更好的方法是什麼?

回答

0

試試這個: -

<?php 

ob_start(); 
ob_clean(); 

$fileName = 'somefile.csv'; 

header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header('Content-Description: File Transfer'); 
header("Content-type: text/csv"); 
header("Content-Disposition: attachment; filename={$fileName}"); 
header("Expires: 0"); 
header("Pragma: public"); 

$fh = @fopen('php://output', 'w'); 

global $wpdb; 
$query = "SELECT nome, email FROM {$wpdb->prefix}coming_soon_lista_email"; 
$results = $wpdb->get_results($query, ARRAY_A); 
$headerDisplayed = false; 

foreach (unserialize($_GET['asd']) as $data) { 
    if (!$headerDisplayed) { 
     fputcsv($fh, array_keys($data)); 
     $headerDisplayed = true; 
    } 
    fputcsv($fh, $data); 
} 
fclose($fh); 
exit; 
?> 
+0

它沒有工作=('不能修改頭信息 - 頭已經發送(輸出開始在wp-admin \ menu-header.php:107' – ghaschel

+0

比刪除' ob_start();'從這個文件中添加'ob_start();'到你的'wp-config.php'文件中...... –

+0

我不應該編輯wp-config,因爲它將被用於多個wordpress複製... – ghaschel

0

我建設我Wordpress plugin時有同樣的問題。我通過在我的插件的構造函數中插入if語句來解決這個問題,該語句會中斷並輸出csv。

這是我做了我的

function __construct(){ 
    if($_GET['export'] == true && $_GET['page'] == 'cwd-management' && is_admin()) 
    { 
     $csv = ''; 
     foreach ($this->getAll() as $row) { // getAll() just returns all data in a custom table 
      $csv .= $row->ref . "," . $row->data . "\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=\"cwd-export_" . date("Y-m-d_H-i-s") . ".csv\";"); 
     header("Content-Transfer-Encoding: binary"); 

     echo $csv; 
     exit; 
    } 
} 

不知道你的表結構我不能給出一個完整的例子,但希望你可以使用我的代碼添加到您的插件類。然後只是提供一個鏈接,如果符合