如何解决如何使用PHP下载CSV文件
我的代码的目的是从我的数据库下载一个CSV文件。但是,文件的内容显示在网页上,而不是下载文件。另外,当我将下载功能移到我的for循环中时,它会下载CSV文件,但无法访问该网页。这是整个代码:
<html>
<style>
table,th,td{
padding: 10px;
border: 1px solid black;
border-collapse: collapse;
}
table,.center{
text-align: center;
margin-left: auto;
margin-right: auto;
}
</style>
<?php
function array_to_csv_download($array,$filename = "export.csv",$delimiter = ",") {
// open the "output" stream
// see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq
header("Content-disposition: attachment; filename=test.csv");
header("Content-Type: text/csv");
ob_clean();
flush();
$f = fopen('php://output','w');
foreach ($array as $line) {
fputcsv($f,$line,$delimiter);
}
readfile($f);
ob_end_clean();
}
mysql_connect("localhost","root","");
mysql_select_db("gograb");
$filename = $_FILES["file"]["tmp_name"];
echo "<table id='center'>"
. "<tr>"
. "<th>"
. "Number"
. "</th>"
. "<th>"
. "Brand"
. "</th>"
. "<th>"
. "Item Name"
. "</th>"
. "<th>"
. "Description"
. "</th>"
. "<th>"
. "Weight"
. "</th>"
. "<th>"
. "Variant1 Name"
. "</th>"
. "<th>"
. "Variant1 Value"
. "</th>"
. "<th>"
. "Variant2 Name"
. "</th>"
. "<th>"
. "Variant2 Value"
. "</th>"
. "<th>"
. "Price"
. "</th>"
. "<th>"
. "Barcode"
. "</th>"
. "<th>"
. "Department"
. "</th>"
. "<th>"
. "Collections"
. "</th>"
. "<th>"
. "Type"
. "</th>"
. "<th>"
. "Tag"
. "</th>"
. "<th>"
. "Image URL"
. "</th>"
. "</tr>";
if ($_POST["action"] == "Find Duplicate") {
if (($h = fopen("{$filename}","r")) !== FALSE) {
$skip_var = 1;
while (($data = fgetcsv($h,30000,",")) !== FALSE) {
if ($skip_var == 1) {
$skip_var += 1;
continue;
}
echo "<tr>";
$select = "SELECT * FROM global_catalog where Barcode='$data[10]'";
$query = mysql_query($select);
if (mysql_num_rows($query) > 0) {
$row = mysql_fetch_assoc($query);
foreach ($data as $field => $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
$big_array[] = $data;
}
}
array_to_csv_download($big_array);
}
$counter = 0;
if ($_POST["action"] == "Find New") {
if (($h = fopen("{$filename}",")) !== FALSE) {
if ($skip_var == 1) {
$skip_var += 1;
continue;
}
echo "<tr>";
$select = "SELECT * FROM global_catalog where Barcode='$data[10]'";
$query = mysql_query($select);
if (mysql_num_rows($query) == 0) {
$counter+=1;
$row = mysql_fetch_assoc($query);
foreach ($data as $field => $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
}
fclose($h);
}
}
echo "</table>";
?>
</html>
解决方法
页面顶部正在输出HTML,这将阻止发送标头。
您应该将整个if ($_POST["action"] == "Find Duplicate") { ... }
块移到页面的顶部,并在exit();
函数末尾添加对array_to_csv_download()
的调用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。