PHP导出MySql Excel工作表不会工作

我得到的错误消息是与标题。 我正在使用mysqli_我在空白页上使用mysql_来testing它。 当我把它放到我的真实页面上的点击时,它告诉我我不能使用mySql_,因为它是旧的,所以将它转换为mySqli_。 我现在得到的错误消息是:

“警告:无法修改标题信息 – 已由(在/xx/xxx/xxx.php:183开始的输出)在/xxx/xxx/xxx.php在232行发送的标题警告:不能修改标题信息 – 已经由(输出在/xxx/xxx/xxx.php:183开始)位于/xxx/xxx/xxx.php在233行致命错误:调用未定义的函数outputcsv()在/xxx/xxx/xxx.php在第237行“

require_once 'dbconfig.php'; $conn = new mysqli("xxxx", "xxxx", $password, $dbname);//host, user, password, database $result = $conn->query('SELECT * FROM reports') or die(mysqli_error()); //these two lines are the lines 232 and 233 header('Content-Type: text/csv'); // tell the browser to treat file as CSV header('Content-Disposition: attachment;filename=report.csv'); // tell browser to download a file in user's system with name export.csv $row = mysqli_fetch_assoc($result); // Get the column names if ($row) { outputcsv(array_keys($row)); // It wil pass column names to outputcsv function } //this line here is 237 while ($row) { outputcsv($row); // loop is used to fetch all the rows from table and pass them to outputcsv func $row = mysqli_fetch_assoc($result); } function outputcsv($fields) { $csv = ''; foreach ($fields as $field) { $csv .= '"' . $field . '",'; } $csv .= "\r\n"; //Give a carriage return and new line space after each record echo $csv; } 

您需要在configuration文件中设置输出缓冲区

要么

只需在代码的第一行写ob_start()。

而且我还build议以xls格式导出​​以获得更好的兼容性。

你需要查找PHP输出缓冲 。

您正在呼叫或发送headers already sent by (output started at /xx/xxx/xxx.php:183) 183行headers already sent by (output started at /xx/xxx/xxx.php:183)某些数据,然后修改头。 您可以使用OB缓冲您将发送到浏览器的信息,修改标题,然后刷新缓冲区。

 ob_start(); require_once 'dbconfig.php'; $conn = new mysqli("xxxx", "xxxx", $password, $dbname);//host, user, password, database $result = $conn->query('SELECT * FROM reports') or die(mysqli_error()); //these two lines are the lines 232 and 233 header('Content-Type: text/csv'); // tell the browser to treat file as CSV header('Content-Disposition: attachment;filename=report.csv'); // tell browser to download a file in user's system with name export.csv $row = mysqli_fetch_assoc($result); // Get the column names if ($row) { outputcsv(array_keys($row)); // It wil pass column names to outputcsv function } //this line here is 237 while ($row) { outputcsv($row); // loop is used to fetch all the rows from table and pass them to outputcsv func $row = mysqli_fetch_assoc($result); } function outputcsv($fields) { $csv = ''; foreach ($fields as $field) { $csv .= '"' . $field . '",'; } $csv .= "\r\n"; //Give a carriage return and new line space after each record echo $csv; } ob_flush(); 

您也可以使用ob_get_flush()ob_get_contents()将缓冲区的内容返回给一个string,允许从函数等返回。注意: ob_get_contents()不清除缓冲区,它只是返回内容。

我还看到一个关于outputcsv($ fields)没有被定义的错误,但是在解释器可以通过标题问题之后可能会清除这个错误。