簡體   English   中英

強制在Wordpress插件中下載文件

[英]Force file download inside a wordpress plugin

我在制作.csv文件並將其下載到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;
?>

在這種情況下,哪種方法更好?

嘗試這個: -

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

構建我的Wordpress插件時,我遇到了同樣的問題。 我通過在插件的構造函數中使用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;
    }
}

在不知道您的表結構的情況下,我無法給出完整的示例,但希望您可以使用我的代碼將其添加到插件類中。 然后只提供符合if陳述的鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM