我有两个脚本,一个包含一个写.csv文件的函数,另一个调用该函数。
文件写入功能。
<?php
include("config.php");
function exportMysqlToCsv($subid){
$sql = "SELECT * FROM campaigns";
$results = mysql_query($sql);
$getpub = mysql_query("SELECT * FROM `publishers` WHERE `username` = '".$_SESSION['username']."'");
$pinfo = mysql_fetch_array($getpub);
// Pick a filename and destination directory for the file
// Remember that the folder where you want to write the file has to be writable
$filename = "campaigns_export_pub".$pinfo['id'].".csv";
// Actually create the file
// The w+ parameter will wipe out and overwrite any existing file with the same name
$handle = fopen($filename, 'w+');
// Write the spreadsheet column titles / labels
fputcsv($handle, array('Campaign ID','Campaign Name','Promoting URL','Category','Rate','Countries','Description','Requirements'));
// Write all the user records to the spreadsheet
while($row = mysql_fetch_array($results))
{
$url = "http://www.rageleads.com/click.php?aid=".$pinfo['id']."&cid=".$row['id']."&sid=".$subid."";
fputcsv($handle, array($row['id'], $row['name'], $url, $row['category'], $row['rate'], $row['countries'], $row['description'], $row['requirements']));
}
// Finish writing the file
fclose($handle);
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename='.$filename");
readfile($filename);
unlink($filename);
exit();
}
?>
函数调用。
<?php
include("config.php");
include("header.php");
include("functions.php");
include("export.php");
$subid = cleanQuery($_POST['subid']);
if($_POST['submit']){
exportMysqlToCsv($subid);
}
print"
<div id='center'>
<table class='balances'>
<form method='POST' action=''>
<tr>
<td>Sub ID Placeholder:</td>
<td><input type='text' name='subid' /></td>
</tr>
<tr>
<td></td>
<td><input type='submit' name='submit' value='Export' /></td>
</tr>
</form>
</table>
</div>";
include("footer.php");
?>
我遇到的问题是不是按照函数中定义的方式编写.csv文件,而是编写函数调用所在页面的实际html代码,然后添加定义的信息。功能。这是我第一次写一个文件写入功能,所以我确信我已经把某些东西搞砸了,但我不太确定我做错了什么。
如果我将export.php设置为不是函数,只需转到它编写的页面并以正确的格式下载csv文件。
有什么建议吗?
编辑:我不知道为什么我之前没有这样做,但当我检查它在我的服务器上创建的csv文件时,一切都是正确的,所以标题中的内容正在发送此信息额外的信息,但我不知道是哪一个,或为什么。
答案 0 :(得分:1)
试试这个。如果您发送CSV数据,请确保它是您发送的唯一内容。否则,发送HTML文件。您明确地同时发送了HTML和CSV。
$subid = cleanQuery($_POST['subid']);
if($_POST['submit']) {
exportMysqlToCsv($subid);
} else {
include("config.php");
include("header.php");
include("functions.php");
include("export.php");
print"
<div id='center'>
<table class='balances'>
<form method='POST' action=''>
<tr>
<td>Sub ID Placeholder:</td>
<td><input type='text' name='subid' /></td>
</tr>
<tr>
<td></td>
<td><input type='submit' name='submit' value='Export' /></td>
</tr>
</form>
</table>
</div>";
include("footer.php");
}