简体   繁体   English

PHP导出到Excel文件为我提供了按列提供的源代码

[英]PHP export to Excel file gives me source code in columns

I feel like I'm making a simple mistake but I can't seem to figure out what. 我觉得自己犯了一个简单的错误,但似乎无法弄清楚。

I have some code for exporting a mySQL table to an Excel file. 我有一些用于将mySQL表导出到Excel文件的代码。

However, when I do the export, the entire HTML source code gets exported along with my data. 但是,当我执行导出时,整个HTML源代码会与我的数据一起导出。 I open the file in Excel and my table data in there but it's also got all the HTML inside. 我在Excel中打开文件,并在其中打开表数据,但其中也包含所有HTML。

What could be causing all the source code to be exported along with the data? 是什么导致所有源代码与数据一起导出?

I should mention that I'm using this code as part of a Wordpress plugin I'm writing. 我应该提到的是,我将此代码用作我正在编写的Wordpress插件的一部分。 When I test the export outside wordpress, it works fine. 当我测试wordpress外部的导出时,效果很好。 But when I try to export from a Wordpress admin page, I get all the extra HTML source code. 但是,当我尝试从Wordpress管理页面导出时,会获得所有额外的HTML源代码。

Try this code. 试试这个代码。

$host = 'localhost';
$user = 'mysqlUser';
$pass = 'myUserPass';
$db = 'myDatabase';
$table = 'products_info';
$file = 'export';

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());

mysql_select_db($db) or die("Can not connect.");


$res = mysql_query("SELECT * FROM $table");

// fetch a row and write the column names out to the file
$row = mysql_fetch_assoc($res);
$line = "";
$comma = "";
foreach($row as $name => $value) {
    $line .= $comma . '"' . str_replace('"', '""', $name) . '"';
    $comma = ",";
}
$line .= "\n";
fputs($fp, $line);

// remove the result pointer back to the start
mysql_data_seek($res, 0);

// and loop through the actual data
while($row = mysql_fetch_assoc($res)) {

    $line = "";
    $comma = "";
    foreach($row as $value) {
        $line .= $comma . '"' . str_replace('"', '""', $value) . '"';
        $comma = ",";


    }
     $line .= "\n";
    fputs($fp, $line);

}

fclose($fp);
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="export.csv"');
readfile('export.csv'); 

Thanks, 谢谢,

Kanji 汉子

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

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