下载CSV后显示成功消息

时间:2017-06-08 11:58:32

标签: php wordpress

我开发了一个小型Wordpress插件,可以下载为CSV文件用户'来自数据库的数据。

一切正常,但我在解决如何显示成功消息时遇到了问题。

在负责数据导出的方法代码下面:

/*
* Export CSV File
*/
public function export_CSV()
{

    if ($this->users) {

        $fileName =  "Export_users_" . date("Y-m-d_H:i:s", time());
        $fileName = $fileName.".csv";
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header('Content-Description: File Transfer');
        header('Content-Encoding: UTF-8');
        header("Content-type: application/csv;charset=UTF-8");
        header("Content-Disposition: attachment; filename={$fileName}");
        header("Expires: 0");
        header("Pragma: public");
        echo "\xEF\xBB\xBF"; // UTF-8 BOM
        $fh = @fopen( 'php://output', 'w' );
        $headerDisplayed = false;

        foreach ($this->users as $user) {

            if($user) {


                $user_meta = get_user_meta($user->data->ID);

                //Push user meta into $user array

                foreach($user_meta as $key => $var)
                {
                    $user->data->$key = trim($var[0]);
                }

                //convert object in array;

                $usersArray = (array)$user->data;

                // Add a header row if it hasn't been added yet

                if ( $headerDisplayed == false ) {

                    // Use the keys from $directory as the titles

                    fputcsv($fh, array_keys($usersArray));

                    $headerDisplayed = true;
                }

                // Put the data into the stream

                fputcsv($fh,$usersArray);


            }//end if

        }//end foreach

        // Close the file

        fclose($fh);

        // Users exported successfully

        $this->response = "Users exported successfully!";

        // Make sure nothing else is sent

        exit;


    } else {

        // No results found

        $this->response = "Sorry, no results found!";

    }

}

我必须使用exit,否则CSV文件将包含页面的所有html。有没有办法运行javascript文件来更新前端的消息?

提前致谢!

2 个答案:

答案 0 :(得分:0)

首先:

将下载详细信息放在单独的页面中。您只能发送一次标题,这是您在发送csv标头后无法打印html的原因之一。

其次,如果函数成功,则可以创建if / else语句。如果确实如此,您可以添加一些JS代码,如下例所示:

if($download = true) {
   echo "<script> alert('Download succesfull!'); </script>";
}
else {
   echo "<script> alert('Download failed!'); </script>";
}

我不确定它是否能像上面一样工作,因为它是服务器事件。另一种可能的解决方案是创建ServerEventCheck。

答案 1 :(得分:0)

我通过将响应消息作为变量传递到标题中来提出解决方案。

$this->response = "Users downloaded Successfully!";
header("Location:?page=export-users&response=".$this->response);

然后像这样检索它:

<?php if(isset($_GET['response'])){ ?>
        <div class="updated notice">
            <p><?php echo __( $_GET['response']);?></p>
        </div><!--error notice-->
    <?php } ?>