简体   繁体   English

PHP-当浏览器保存csv文件时,csv的内容会在csv文件的开头附加html页面

[英]PHP - When browsers save csv file, the content of the csv appends the html page at beginning of csv file

My php code saves the .csv file on the server. 我的PHP代码将.csv文件保存在服务器上。 When I get the .csv file directly from server, its content is good and I can view it in Excel. 当我直接从服务器获取.csv文件时,它的内容很好,可以在Excel中查看它。 But in my webpage, when I click to save the file, the content saved on my computer is bringing the content of the html file, followed by the content of csv file. 但是在我的网页上,当我单击以保存文件时,保存在计算机上的内容将显示html文件的内容,然后显示csv文件的内容。 What could be wrong ? 有什么问题吗?

Here is the piece of code where I have issue: 这是我遇到的问题:

while ($row = oci_fetch_array($my_query, OCI_ASSOC+OCI_RETURN_NULLS))
{       
    //store content in csv format into $mymessage
}

$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
fwrite($handle, $mymessage);
fclose($handle);

header("Content-type: application/x-file-to-save");
header("Content-Disposition: attachment; filename=$my_file");
readfile("$my_file");
exit;

============================================================ ================================================== ==========

Here's how the content looks like: 内容如下所示:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Cp1252">
<title>ABCDEF...</title>
</head>
<body>
<font size="4" color=blue><a><b><i><u>12345678</u></i></b></a></font>
<br></br>
...

CSV REPORT EXTRACTED AS OF, 2014/03/25 08:18:16

SERVER,APP-SERVER
server1,weblogic
server2,jboss
server3,weblogic
server4,weblogic
server5,websphere
...

Appreciate in advance. 提前欣赏。

this seems to be like some kind of routing problem. 这似乎就像某种路由问题。 Your php page charging the CSV data should be the only one called. 收费CSV数据的php页面应该是唯一被调用的页面。 But it seems like you are using a framework or you may have an include somewhere or you have a rewrite on your server. 但是似乎您正在使用框架,或者您可能在某个位置包含了include,或者在服务器上进行了重写。

Well, I got it resolved. 好吧,我解决了。 I had to add ob_end_clean() before $handle() and before first header(). 我必须在$ handle()之前和第一个header()之前添加ob_end_clean()。 With that done, any buffered output was cleared out and csv file was saved with no "extra" content. 完成此操作后,将清除所有缓冲的输出,并保存不包含“多余”内容的csv文件。

Thank you all that spent time trying to help me. 谢谢所有花时间尝试帮助我的人。

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

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