2013-01-04 32 views
6

Ho bisogno di esportare i dati in una tabella in un file csv. Sono in grado di ottenere i dati bene ma il file CSV non viene generato dal browser.esportazione in wordpress csv

Il mio codice è come questo: è il problema con le intestazioni. Sto ottenendo solo l'output con le virgole valori separati ma non ottenendo file CSV.

/* Converting data to CSV */ 

public function CSV_GENERATE($getTable) 
{ 
    ob_clean(); 
    global $wpdb; 
    $field=''; 
    $getField =''; 

    if($getTable){ 
     $result = $wpdb->get_results("SELECT * FROM $getTable"); 
     $requestedTable = mysql_query("SELECT * FROM ".$getTable); 
     // echo "hey";die;//var_dump($result);die; 

     $fieldsCount = mysql_num_fields($requestedTable); 

     for($i=0; $i<$fieldsCount; $i++){ 
      $field = mysql_fetch_field($requestedTable); 
      $field = (object) $field;   
      $getField .= $field->name.','; 
     } 

     $sub = substr_replace($getField, '', -1); 
     $fields = $sub; # GET FIELDS NAME 
     $each_field = explode(',', $sub); 
     $csv_file_name = $getTable.'_'.date('Ymd_His').'.csv'; 
     # CSV FILE NAME WILL BE table_name_yyyymmdd_hhmmss.csv 

     # GET FIELDS VALUES WITH LAST COMMA EXCLUDED 
     foreach($result as $row){ 
      for($j = 0; $j < $fieldsCount; $j++){ 
       if($j == 0) $fields .= "\n"; # FORCE NEW LINE IF LOOP COMPLETE 
       $value = str_replace(array("\n", "\n\r", "\r\n", "\r"), "\t", $row->$each_field[$j]); # REPLACE NEW LINE WITH TAB 
       $value = str_getcsv ($value , ",", "\"" , "\\"); # SEQUENCING DATA IN CSV FORMAT, REQUIRED PHP >= 5.3.0 
       $fields .= $value[0].','; # SEPARATING FIELDS WITH COMMA 
      } 
      $fields = substr_replace($fields, '', -1); # REMOVE EXTRA SPACE AT STRING END 
     } 

     header("Content-type: text/x-csv"); # DECLARING FILE TYPE 
     header("Content-Transfer-Encoding: binary"); 
     header("Content-Disposition: attachment; filename=".$csv_file_name); # EXPORT GENERATED CSV FILE 
     header("Pragma: no-cache"); 
     header("Expires: 0"); 
     header("Content-type: application/x-msdownload"); 
     //header("Content-Disposition: attachment; filename=data.csv"); 

     return $fields; 
    } 

risposta

6

Ora funziona perfettamente. possiamo usare questo come plugin. Ho modificato il post this. grazie a sruthi sri.

Spero che questo aiuti qualcuno :)

<?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>Export the Subscribers'; 
} 

/** 
* 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(); 
+0

Grazie per la tua lezione ma quando lo uso il mio csv non è formattato correttamente. Voglio dire, non ho colonne –

+0

Mi dispiace. Non riesco a ottenere quello che ti manca, ma ha funzionato perfettamente per me. stesso codice che ho incollato in questo post. – Developer

+0

Microsoft Excel fa schifo ... per avere un documento formattato per colonne, ho dovuto inserire un punto e virgola invece di una virgola ... –

2

Non ne sono sicuro, ma ci sono alcune cose che potrebbero essere.

Le tue parentesi non corrispondono: ti manca una chiusura } da qualche parte.

In realtà non stai inviando il contenuto generato da nessuna parte, a meno che non lo stia facendo nella routine di chiamata? Forse intendi echo $fields;, non return $fields;?

Stai chiamando ob_clean() - hai attivato il buffering dell'uscita? Forse vuoi dire ob_end_clean() - per scartare il buffer e disattivare il buffering?

Sto creando un CSV per l'esportazione; si sta lavorando con solo le seguenti intestazioni:

header('Content-Type: text/csv'); 
header('Content-Disposition: attachment; filename="' . $csv_file_name . '"'); 
header('Pragma: no-cache'); 
header('Expires: 0'); 

In termini di differenze con le chiamate:

  1. si sta inviando due Content-Type intestazioni
  2. ho citazioni intorno al mio nome
  3. I' m non specificando un Content-Transfer-Encoding

Non so che nessuno dei Le differenze di ose sono legate al tuo problema, le sto solo elencando nel caso in cui aiutino.

+1

grazie per la risposta e l'ora. è il problema con l'intestazione amico. non vengono caricati per primi. Ho provato alcune cose come questa che ora funzionano come plugin con un singolo file. – Developer

+0

Fa sembrare il buffering di uscita che ho menzionato nella mia risposta? – Hobo

3

Sono un disastro in ritardo, ma ha fatto una piccola 'miglioramento' per il codice voi ragazzi lavorato e vorrei condividere. Se il codice incollato nel file .php del plugin principale non è necessario passare attraverso i 3 passaggi. Basta modificare i valori nella parte inferiore dello script come richiesto. Mi piace tenerlo pulito ma con molti commenti per voi ragazzi.

Per i principianti che potrebbero aver bisogno questo e per aggiungere la flessibilità da usare per chiunque:

  1. aggiungere prima variabile globale define('MY_PLUGIN_DIR', plugin_dir_path(__FILE__));
  2. Dopo di che aggiungere require_once(PARTS_MY_PLUGIN_DIR . '/databasestuff/table_to_csv.php')
  3. Sotto your_plugin_directory/databasestuff/table_to_csv.php salvare la seguente classe e cambiare l'ultimo poche righe come richiesto.
  4. apportare modifiche per le ultime righe

    class export_table_to_csv{ 
    
        private $db; 
        private $table_name; 
        private $separator; 
    
    
        function __construct($table_n, $sep, $filename){ 
    
        global $wpdb;            //We gonna work with database aren't we? 
        $this->db = $wpdb;           //Can't use global on it's own within a class so lets assign it to local object. 
        $this->table_name = $table_n;        
        $this->separator = $sep; 
    
        $generatedDate = date('d-m-Y His');       //Date will be part of file name. I dont like to see ...(23).csv downloaded 
    
        $csvFile = $this->generate_csv();       //Getting the text generated to download 
        header("Pragma: public"); 
        header("Expires: 0"); 
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
        header("Cache-Control: private", false);     //Forces the browser to download 
        header("Content-Type: application/octet-stream"); 
        header("Content-Disposition: attachment; filename=\"" . $filename . " " . $generatedDate . ".csv\";"); 
        header("Content-Transfer-Encoding: binary"); 
    
        echo $csvFile;            //Whatever is echoed here will be in the csv file 
        exit; 
    
        } 
    
    
        function generate_csv(){ 
    
        $csv_output = '';           //Assigning the variable to store all future CSV file's data 
        $table = $this->db->prefix . $this->table_name;    //For flexibility of the plugin and convenience, lets get the prefix 
    
        $result = $this->db->get_results("SHOW COLUMNS FROM " . $table . ""); //Displays all COLUMN NAMES under 'Field' column in records returned 
    
        if (count($result) > 0) { 
    
         foreach($result as $row) { 
          $csv_output = $csv_output . $row->Field . $this->separator; 
         } 
         $csv_output = substr($csv_output, 0, -1);    //Removing the last separator, because thats how CSVs work 
    
        } 
        $csv_output .= "\n"; 
    
        $values = $this->db->get_results("SELECT * FROM " . $table . "");  //This here 
    
        foreach ($values as $rowr) { 
         $fields = array_values((array) $rowr);     //Getting rid of the keys and using numeric array to get values 
         $csv_output .= implode($this->separator, $fields);  //Generating string with field separator 
         $csv_output .= "\n"; //Yeah... 
        } 
    
        return $csv_output; //Back to constructor 
    
        } 
    } 
    
    // Also include nonce check here - https://codex.wordpress.org/WordPress_Nonces 
    if(isset($_POST['processed_values']) && $_POST['processed_values'] == 'download_csv'){ //When we must do this 
        $exportCSV = new export_table_to_csv('table_name',';','report');    //Make your changes on these lines 
    } 
    

tenere a mente:

  1. prefisso Tabella sarà aggiunto il nome della tabella.
  2. Questo script utilizza le funzioni principali di WordPress, il che significa che le ultime 3 righe sono letteralmente tutte le modifiche da apportare affinché funzioni.
2

Semplicemente apportando alcune piccole modifiche a @Developer poiché non era abbastanza impegnativo nell'amministratore o nel download di CSV. Ma ora sarà :):

<?php 

/** 
* CSV Exporter bootstrap file 
* 
* This file is read by WordPress to generate the plugin information in the plugin 
* admin area. This file also includes all of the dependencies used by the plugin, 
* registers the activation and deactivation functions, and defines a function 
* that starts the plugin. 
* 
* @since    1.0.0 
* @package   CSV Export 
* 
* @wordpress-plugin 
* Plugin Name:  CSV Export 
* Plugin URI:  http://example.com/plugin-name-uri/ 
* Description:  exports csvs derrr 
* Version:   1.0.0 
* Author:   Your Name or Your Company 
* Author URI:  http://example.com/ 
* License:   GPL-2.0+ 
* License URI:  http://www.gnu.org/licenses/gpl-2.0.txt 
* Text Domain:  csv-export 
* Domain Path:  /languages 
*/ 
class CSVExport { 

    /** 
    * Constructor 
    */ 
    public function __construct() { 
    if (isset($_GET['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>'; 
    echo '<p><a href="?page=download_report&report=users">Export the Subscribers</a></p>'; 
    } 

    /** 
    * Converting data to CSV 
    */ 
    public function generate_csv() { 
    $csv_output = ''; 
    $table = 'wp_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(); 

Basta creare un file chiamato csv_export.php metterlo in una plugins/csv_export/e sei GTG!

Problemi correlati