gpt4 book ai didi

php生成excel并下载

转载 作者:行者123 更新时间:2023-12-04 21:24:38 25 4
gpt4 key购买 nike

我有一个网站,它有一个简单的功能来生成包含数组数据的 Excel,然后提供用户下载。

header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=spreadsheet.xls" );
echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
echo 'John' . "\t" . 'Doe' . "\t" . '555-5555' . "\n";

上面的代码是用来测试的,但是我只在excel中从网站上得到了一些html代码,而不是数据。

请问为什么会这样?
谢谢!

最佳答案

确保在 header 调用之前不发送任何内容。

// At the begginnig of script...
ob_start();

// ... do some stuff ...

ob_get_clean();

header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=spreadsheet.xls" );
echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
echo 'John' . "\t" . 'Doe' . "\t" . '555-5555' . "\n";
die();

如果您需要处理整个脚本,另一种方法是:
<?php
// At the beggining...
ob_start();
$content="";
$normalout=true;

// ... do some stuff ...

// i guess if some condition is true...
$content=ob_get_clean();
$normalout=false;
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=spreadsheet.xls" );
echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
echo 'John' . "\t" . 'Doe' . "\t" . '555-5555' . "\n";

// Here you could die() or continue...
ob_start();

// ... rest of execution ...

$content.=ob_get_clean();
if($normalout)
{
echo($content);
} else {
// Excel provided no output.
}
?>

这应该有效。

关于php生成excel并下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24013931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com