【问题标题】:export to csv wordpress导出到 csv wordpress
【发布时间】:2012-12-19 02:10:14
【问题描述】:

我需要将数据导出到 csv 文件的一个表中。我可以正常获取数据,但浏览器没有生成 CSV 文件。

我的代码是这样的:标题的问题。我只得到带有逗号分隔值的输出,但没有得到 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; 
    }

【问题讨论】:

    标签: php wordpress csv header


    【解决方案1】:

    我不确定,但有几件事可能是这样。

    您的大括号不匹配 - 您在某处缺少结束 }

    您实际上并没有将生成的内容发送到任何地方,除非您在调用例程中这样做?也许你的意思是echo $fields;,而不是return $fields;

    您正在呼叫ob_clean() - 您是否打开了输出缓冲?也许您的意思是ob_end_clean() - 丢弃缓冲区并关闭缓冲?

    我正在创建一个用于导出的 CSV;它仅使用以下标头:

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

    就与您通话的差异而言:

    1. 您要发送两个 Content-Type 标头
    2. 我的文件名有引号
    3. 我没有指定Content-Transfer-Encoding

    我不知道这些差异是否与您的问题有关,我只是列出它们以防万一。

    【讨论】:

    • 感谢您的回复和时间。这是标题朋友的问题。他们没有先被加载。我尝试了一些像这样的东西,现在作为一个插件使用一个文件。
    • 听起来像是我在回答中提到的输出缓冲?
    【解决方案2】:

    现在运行良好。我们可以将其用作插件。我修改了this 帖子。感谢 sruthi sri。

    希望这对某人有所帮助:)

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

    【讨论】:

    • 感谢您的课程,但是当我使用它时,我的 csv 格式不正确。我的意思是我没有列
    • 对不起。我实际上得到了你所缺少的东西,但它对我来说非常有效。我在这篇文章中粘贴的相同代码。
    • Microsoft Excel 糟透了...为了按列格式化文档,我不得不用分号而不是逗号...
    【解决方案3】:

    我是一个大器晚成的人,但对你们编写并希望分享的代码做了一个小的“改进”。 如果代码粘贴在主插件 .php 文件中,则无需执行这 3 个步骤。只需根据需要更改脚本底部的值即可。我喜欢保持整洁,尽管有很多 cmets 供你们使用。

    对于可能需要此功能并增加每个人使用灵活性的初学者:

    1. 首先添加全局变量define('MY_PLUGIN_DIR', plugin_dir_path(__FILE__));
    2. 之后添加require_once(PARTS_MY_PLUGIN_DIR . '/databasestuff/table_to_csv.php')
    3. your_plugin_directory/databasestuff/table_to_csv.php 下保存以下类并根据需要更改最后几行。
    4. 调整最后几行

      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
      }
      

    记住:

    1. 表前缀将添加到表名中。
    2. 此脚本使用核心 WordPress 函数,这意味着您只需更改最后 3 行即可使其正常工作。

    【讨论】:

    • 这种方式在浏览器上输出数据
    • @Khadreal,标题使浏览器将其作为文件下载。如果您尝试过,则需要调整标题以指定内容类型。
    【解决方案4】:

    只需对@Developer 进行一些小调整,因为它并没有在管理员中完全启动,也没有下载 csv。但现在它会:):

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

    只需创建一个名为 csv_export.php 的文件,将其放入 plugins/csv_export/ 即可!

    【讨论】:

    • 真的很有用,但是如何防止未登录的用户下载 CSV?他们无法访问管理页面,但他们可以访问 URL 以触发下载
    • 检查文档中的 is_admin() 和 current_user_can() 函数
    【解决方案5】:

    我遇到了同样的问题。我发现问题不是标题代码,而是你点击导出的链接。你需要添加一个名为“noheader”的参数:

        <a href="admin.php?page=export&export=posts&noheader=1">Export</a> 
    

    我用这个问题中提到的完全相同的标头代码替换了我的代码,它也可以正常工作。 我的导出过程代码如下:

    if( isset( $_GET['export'] ) ) {
    
        $csv = generate_csv();
    
        $filename = 'results.csv';
        $now = gmdate('D, d M Y H:i:s') . ' GMT';
    
        header( 'Content-Type: application/octet-stream' ); // tells browser to download
    
        header( 'Content-Disposition: attachment; filename="' . $filename .'"' );
        header( 'Pragma: no-cache' ); // no cache
        header( 'Expires: ' . $now ); // expire date
    
        echo $csv;
        exit;
    }
    

    最后两个标头告诉浏览器不要缓存导出的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      • 2017-12-01
      • 2017-11-17
      • 2017-02-20
      • 1970-01-01
      相关资源
      最近更新 更多