简体   繁体   English

PHP csv 下载与服务器上的文件副本不同

[英]PHP csv download is different to the copy of the file on the server

I'm trying to make a PHP page that queries a database, creates a CSV in the tmp folder then sends that csv to the browser to download, but the file that downloads contain only the last echo in the PHP script, not the file that is stored on the server (that file is saved on the server is perfect).我正在尝试制作一个查询数据库的 PHP 页面,在 tmp 文件夹中创建一个 CSV,然后将该 csv 发送到浏览器进行下载,但下载的文件仅包含 PHP 脚本中的最后一个回显,而不是该文件存储在服务器上(该文件保存在服务器上是完美的)。

<?php


$db_host = "localhost"; //can be "localhost" for local development
$db_username = "root";
$db_password = "";
$db_name = "seinventory";
$link = mysqli_connect($db_host,$db_username,$db_password,$db_name) or die(mysqli_error($link));


// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$softwareName = $_GET['soft'];

$result = mysqli_query($link,"SELECT * FROM `seinventory` WHERE software LIKE '%$softwareName%' or apps LIKE '%$softwareName%'");
$timeStamp = date('d.m.Y-h.i.s');
$csvFile = 'C:/xampp/htdocs/tmp/file.csv';
$new_csv = fopen($csvFile, 'w');
$headings = Array('PC Name','Software Name','Software Version');
fputcsv($new_csv, $headings);
while($row = mysqli_fetch_array($result))
{
    $pcName = $row['pcName'];
    $software = $row['software'];
    $app = $row['apps'];
    $softwareArray = explode(";", $software);
    $appArray = explode(";", $app);
    $multiArray = array_merge($softwareArray, $appArray);
    foreach ( $multiArray as $value ) {
        $singleSoftwareArray = explode(":", $value);
        $softwareItem = $singleSoftwareArray[0];
        $pcName = str_replace('.domain.local', '', $pcName);
        if (stripos($softwareItem, $softwareName)  !== false) {
            $singleArray = Array($pcName, $singleSoftwareArray[0], $singleSoftwareArray[1]);
            fputcsv($new_csv, $singleArray);
        }

}
}
fclose($new_csv);

mysqli_close($link);
    // tell the browser it's going to be a csv file
header('Content-Type: application/csv');
    // tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachment; filename="file.csv";');


//unlink($csvFile);
echo "<script>window.close();</script>";

I read somewhere I'm supposed to put exit;我在某处阅读了我应该退出的地方; after the fclose to stop it writing to the file, but my file on the server is perfect somehow it's being changed during the download process.在 fclose 停止写入文件之后,但我在服务器上的文件是完美的,不知何故它在下载过程中被更改。

You must echo the content of the CSV file to get the correct file.您必须回显 CSV 文件的内容才能获得正确的文件。 Remove the last echo from your code and replace it with this one.从您的代码中删除最后一个 echo 并将其替换为这个。

echo file_get_contents('C:/xampp/htdocs/tmp/file.csv');

As you are storing the file locally you can also redirect the user to a file URL and it should trigger the download.当您在本地存储文件时,您还可以将用户重定向到文件 URL,它应该会触发下载。 You won't have to pass the content-disposition header if you do it.如果你这样做,你就不必传递 content-disposition 标头。 You have to remove lines providing Content-Type, Content-Disposition header, and last echo statement if you decide to do it this way.如果您决定这样做,您必须删除提供 Content-Type、Content-Disposition 标头和最后一个 echo 语句的行。

header("Location: tmp/file.csv");

If you are creating the file just temporarily and removing it afterwards then I suggest you should store the data in memory and echo it afterwards.如果您只是临时创建文件然后删除它,那么我建议您应该将数据存储在内存中并在之后回显。

<?php


$db_host = "localhost"; //can be "localhost" for local development
$db_username = "root";
$db_password = "";
$db_name = "seinventory";
$link = mysqli_connect($db_host,$db_username,$db_password,$db_name) or die(mysqli_error($link));


// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$softwareName = $_GET['soft'];

$result = mysqli_query($link,"SELECT * FROM `seinventory` WHERE software LIKE '%$softwareName%' or apps LIKE '%$softwareName%'");
$timeStamp = date('d.m.Y-h.i.s');
$new_csv = fopen('php://memory', 'w+');
$headings = Array('PC Name','Software Name','Software Version');
fputcsv($new_csv, $headings);
while($row = mysqli_fetch_array($result))
{
    $pcName = $row['pcName'];
    $software = $row['software'];
    $app = $row['apps'];
    $softwareArray = explode(";", $software);
    $appArray = explode(";", $app);
    $multiArray = array_merge($softwareArray, $appArray);
    foreach ( $multiArray as $value ) {
        $singleSoftwareArray = explode(":", $value);
        $softwareItem = $singleSoftwareArray[0];
        $pcName = str_replace('.domain.local', '', $pcName);
        if (stripos($softwareItem, $softwareName)  !== false) {
            $singleArray = Array($pcName, $singleSoftwareArray[0], $singleSoftwareArray[1]);
            fputcsv($new_csv, $singleArray);
        }

    }
}

mysqli_close($link);
    // tell the browser it's going to be a csv file
header('Content-Type: application/csv');
    // tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachment; filename="file.csv";');

// set the file pointer position back to 0
rewind($new_csv);

// echo all the contents from current file pointer position(In this case from start of the file)
echo stream_get_contents($new_csv);

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

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