简体   繁体   English

使用Wordpress用PHP下载CSV文件

[英]Download CSV file with PHP using Wordpress

I have developed a little plugin (for training) for Wordpress. 我为Wordpress开发了一个小插件(用于培训)。 The plugin allows to get the data from a form, save it into a csv file, and then the admin can download the file. 该插件允许从表单获取数据,将其保存到csv文件中,然后管理员可以下载该文件。

My problem is that I can't download this file. 我的问题是我无法下载此文件。 When I click on the download button, it opens a download.php page but nothing more happens. 当我单击下载按钮时,它将打开一个download.php页面,但是什么也没有发生。

I tried different solutions but nothing is working. 我尝试了不同的解决方案,但没有任何效果。 Here is the code of the main file: 这是主文件的代码:

<?php
/*
    Plugin Name: Form to CSV
    Version: 1.0
    Author: Grégory Huyghe
*/


// 1. Shortcode
function ftc_shortcode() {
    readfile("form-to-csv.html", 1);
}

add_shortcode( 'form_csv', 'ftc_shortcode' );

// 1.1 CSS
function ftc_style() {
    wp_register_style('stylesheet', plugins_url('form-to-csv.css', __FILE__));
    wp_enqueue_style('stylesheet');
}

add_action('admin_init', 'ftc_style');


// 2. Onglet plugin dans panneau admin pour voir et télécharger les données collectées
function ftc_menu_item() {
    add_menu_page(
        __( 'Form to CSV', 'textdomain' ),
        'Form to CSV',
        'manage_options',
        'form-to-csv',
        'ftc_menu_plugin',
        'dashicons-portfolio',
        21
    );
}
add_action('admin_menu', 'ftc_menu_item');


// 3. Ecrire les données dans un fichier

// 3.1 Variables
$error = '';
$fname = sanitize_text_field($_POST['prenom']);
$lname = sanitize_text_field($_POST['nom']);
$email = sanitize_email($_POST['email']);
$checkbox = implode(" / ", (array)$_POST['films']);

// 3.2 Clean_text
function clean_text($clean) {
    $trimmed = trim($clean);
    $stripped = stripslashes($clean);
    $special = htmlspecialchars($clean);
    return $clean;
}

// 3.3 Submission form
if(isset($_POST['submit'])) {
    $success = true;

    if(empty($_POST['prenom']) OR empty($_POST['nom']) OR empty($_POST['email'])) {
        $error = '<p>Veuillez réessayer</p>';
    } else {
        $fname = clean_text($_POST['prenom']);
        $lname = clean_text($_POST['nom']);
        $email = clean_text($_POST['email']);
        }

    if($error == '' && $success = true) {

        // Ecriture dans fichier csv
        $file_open = fopen('C:\Users\huygh\Desktop\form-to-csv.csv', 'a');
        $index = count(file('C:\Users\huygh\Desktop\form-to-csv.csv')); 
        if ($index == 0) {
            $index = $index +1;
        } else if ($index > 0) {
            $index = $index +1;
        }

        $form_data = array(
        'id' => $index,
        'prenom' => $fname,
        'nom' => $lname,
        'email' => $email,
        'films' => $checkbox
    );
        fputcsv($file_open, $form_data);
        header( 'Location: index.php' );
        exit();
    }           
}


// 4. Récupérer ses infos dans un custom post accessible depuis le panneau admin. Pas d'envoi de mail.

// 4.1 Récupérer et  Afficher les données dans l'onglet du plugin

function ftc_menu_plugin() {

//    if (isset($_GET['action']) && $_GET['action'] == 'download') {
//        header('Location: C:\Users\huygh\Desktop\form-to-csv.csv');
//        header('Content-Disposition: attachment; filename="form-to-csv.csv"');
//        header("Content-Type: application/force-download");
//        header("Content-Transfer-Encoding: Binary");
//        header("Pragma: no-cache");
//        header("Expires: 0");
//
//        readfile('form-to-csv.csv');
//        
//        echo "toto";
//    }

    $counter = 0;

    echo "<html><body><table>\n\n";

    // Titres du tableau
    echo "<thead>";
    echo "<tr class=\"titles\">";
    echo "<th>ID</th>";
    echo "<th>Prénom</th>";
    echo "<th>Nom</th>";
    echo "<th>Email</th>";
    echo "<th>Sélection</th>";
    echo "</tr>\n";
    echo "</thead>";

    if (($file_read = fopen('C:\Users\huygh\Desktop\form-to-csv.csv', 'r')) !== FALSE) {
        while (($data = fgetcsv($file_read)) !== FALSE && $counter < 20) {
            echo "<tr>";
            $counter++;
            foreach ($data as $cell) {
                    echo "<td>" . $cell . "</td>";
            }
            echo "</tr>\n";
        }
    }
    fclose($file_read);
    echo "\n</table></body></html>";

    // 4.2 Télécharger ce fichier .csv depuis l'onglet du plugin

    ?>
        <a href="download.php" target="_blank">
            <button class="button__csv">Télécharger fichier CSV</button>
        </a>

        <a href="delete.php" target="blank">
            <button class="button__csv button__csv--delete">Supprimer données</button> 
        </a>
<?php

And the code of the download.php: 以及download.php的代码:

<?php
header('Content-Disposition: attachment; filename="form-to-csv.csv"');
header('Content-Type: text/csv');
readfile('C:\\Users\\huygh\\Desktop\\form-to-csv.csv');

As you can see in the main file code, I also tried a solution without using a download.php page, writing the a tag as follow: 正如您在主文件代码中看到的那样,我也尝试了不使用download.php页面的解决方案,并按如下所示编写了一个标记:

<a href="?action=download" target="blank">

But nothing is working. 但是没有任何效果。 Does the problem come from the headers? 问题是否出自标题? Or from Wordpress, something specific to write? 还是从Wordpress中写一些特定的东西?

Here is the screenshot of the response header in the developer tool: 这是开发人员工具中响应标头的屏幕截图: 在此处输入图片说明

As mentioned by Jamie_D , using Location will forward the user to the specified address (like in your 3.3 Submission form code block). Jamie_D所述 ,使用Location会将用户转发到指定地址(如3.3提交表单代码块中所示)。

Remove the line from your code block and you should get the desired download page: 从代码块中删除该行,您应该获得所需的下载页面:

<?php
header('Content-Disposition: attachment; filename="form-to-csv.csv"');
header('Content-Type: text/csv');
// take care to escape the backslashes properly:
readfile('C:\\Users\huygh\\Desktop\\form-to-csv.csv'); 

Additional comments regarding your code: 有关您的代码的其他注释:

  1. Missing underscore in anchor; 锚缺少下划线; it should be: <a href="download.php" target="_blank">Link</a> 它应该是: <a href="download.php" target="_blank">Link</a>

  2. Get rid of the closing ?php> tag: I have seen cases where control / invisible characters after the closing tag caused download troubles as they are then transmitted as part of the file's content. 摆脱掉结尾处的?php>标记:我已经看到了这样的情况:在结束标记后的控制/不可见字符会导致下载问题,因为它们随后作为文件内容的一部分进行传输。

Solution

In the question asker's case the problem was not due to incorrect headers sent to the client but the path pointing to the download.php was incorrect. 在质询者的情况下,问题不是由于发送给客户端的标题不正确,而是指向download.php的路径不正确。

Here is the solution, a simple mistake about the location of download.php which has to be in the wp-admin folder. 这是解决方案,一个关于download.php位置的简单错误,该错误必须在wp-admin文件夹中。

To keep the download.php file into the plugin folder, I wrote a relative URL for the a tag: 为了将download.php文件保留在plugin文件夹中,我为a标签写了一个相对URL:

<a href="/Plugin/wp-content/plugins/form-to-csv/download.php"

Answer of SaschaM78: As you can see the "download.php" can not be found, a 404 means "Page not found". SaschaM78的答案:如您所见,找不到“ download.php”,404表示“找不到页面”。 Make sure that the file really is in "plugins/wp-admin". 确保该文件确实位于“ plugins / wp-admin”中。 – SaschaM78 54 mins ago – SaschaM78 54分钟前

您可以使用HTML5的download属性直接下载文件,

<a href="C:\\Users\\huygh\\Desktop\\form-to-csv.csv" download="form-to-csv.csv">download form-to-csv.csv</a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM