source

csv 워드프레스로 내보내기

ittop 2023. 4. 2. 11:52
반응형

csv 워드프레스로 내보내기

데이터를 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

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

저는 늦었지만, 여러분이 만든 코드를 조금 개선해서 공유하고 싶습니다.메인 플러그인 .php 파일에 코드가 붙여넣어진 경우 3단계를 수행할 필요가 없습니다. 필요에 따라 스크립트 하단의 값을 변경하기만 하면 됩니다.여러분들을 위한 댓글도 많이 달아주시고 깔끔하게 하고 싶어요.

이 기능을 필요로 하는 초보자 및 누구나 사용할 수 있는 유연성을 더하는 초보자용:

  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줄만 변경하면 됩니다.

@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/에 넣으면 gtg가 됩니다.

확실하진 않지만, 몇 가지 있을 수도 있어요.

교정기가 일치하지 않습니다. 클로징이 누락되었습니다.}어딘가에.

실제로 생성된 콘텐츠를 다른 곳으로 전송하지 않는 한 호출 루틴에서 전송하지 않는 건가요?아마 네 말은echo $fields;,것은 아니다.return $fields;?

전화했군요ob_clean()- 출력 버퍼링이 켜져 있습니까?아마 네 말은ob_end_clean()- 버퍼를 폐기하고 버퍼링을 끄시겠습니까?

내보낼 CSV를 만듭니다.이 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

그 차이점들이 당신의 문제와 관련이 있는지는 모르겠지만, 도움이 될 경우를 대비해서 나열해 두겠습니다.

나도 같은 문제를 만났다.문제는 헤더 코드가 아니라 내보내기 위해 클릭하는 링크입니다.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;
}

마지막 두 헤더는 내보낸 내용을 캐시하지 않도록 브라우저에 지시합니다.

언급URL : https://stackoverflow.com/questions/14160511/export-to-csv-wordpress

반응형