在浏览器中打开CSV文件而不是下载HTML

时间:2016-09-27 04:25:58

标签: php html

只是想知道是否有办法在浏览器中打开csv文件而不是下载?

我的代码:

<a href="Myfile.csv">Open</a>

3 个答案:

答案 0 :(得分:3)

您必须添加以下标题。

header ('Content-Type: text/csv');

答案 1 :(得分:3)

if ((day == DayOfWeek.Saturday) || (day == DayOfWeek.Sunday))

设置iframe并将CSV文件网址放入其中。

答案 2 :(得分:1)

  

使用这样的代码:<a href="Myfile.csv">Open</a>,您实际上没有进行任何下载。但是,如果客户端浏览器没有能力读取/呈现文件(在本例中为.csv文件),则会强制用户下载文件。要明确强制执行下载,您必须设置header以告诉浏览器如何处理问题中的文件请求。考虑这个过度简化的脚本:

PHP脚本:包含HTML标记

<?php   // NOTICE THAT THERE IS NO WHITE-SPACE OR OUTPUT BEFORE <?php
        // AND ALSO; NO "echo" STATEMENT AT ALL BEFORE THE if(isset()){} BLOCK.

        if(isset($_GET['d'])){
            $file = htmlspecialchars(trim($_GET['d']));
            processDownload($file);
        }

        function processDownload($fileName) {
            if($fileName){
                $dldFile    = $fileName;
                if(file_exists($fileName)){
                    $size       = @filesize($fileName);
                    header('Content-Description: File Transfer');
                    header('Content-Type: application/octet-stream');
                    header('Content-Disposition: attachment; filename=' . $fileName);
                    header('Content-Transfer-Encoding: binary');
                    header('Connection: Keep-Alive');
                    header('Expires: 0');
                    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                    header('Pragma: public');
                    header('Content-Length: ' . $size);
                    return TRUE;
                }
            }
            return FALSE;
        }

    ?>


    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Download Example</title>
        </head>
        <body>
            <div class="container">
                <div class="col-md-12">
                    <!-- Myfile.csv IS IN THE SAME DIRECTORY AS THIS FILE: index.php -->
                    <!-- OTHERWISE; SET THE PATH TO THE CSV FILE AS VALUE OF d -->
                    <!-- NOTICE THAT THE LINK TO DOWNLOAD HERE IS THE SAME URL -->
                    <!-- WITH A QUERY PARAMETER ?d=Myfile.csv APPENDED TO IT.-->
                    <a href="index.php?d=Myfile.csv">Download CSV</a>
                </div>
            </div>
        </body>
    </html>

希望,这可能会给你一个如何以自己的方式去做的线索。

祝你好运和干杯; - )