我正在Wordpress网站上工作,在那里我有表单字段提交到数据库中的表。在我的functions.php
文件中,我正在创建一个管理页面,该页面的表字段显示在HTML表格中,并且有一个按钮可将表格导出为CSV。该功能正常运行,但是当我将wp_debug
设置为true
时,出现以下错误:
Warning: Cannot modify header information - headers already sent by (output started at /functions.php:119) in /wp-admin/includes/misc.php on line 1126
错误已直接显示在所创建的CSV文件中。当我将wp_debug
设置为false
时,一切都很好,但我宁愿解决该问题也不愿忽略它。
这是我的functions.php
文件中的代码示例:
function submissions_menu() {
add_menu_page( 'Submissions', 'Submissions', 'edit_pages', 'submission-form', 'submission_options', 'dashicons-list-view', '24' );
}
function submission_options() {
global $wpdb;
$submission = $wpdb->get_results( "SELECT * FROM wp_submissions");
echo "<table id='submissions'>";
echo "<tr>
<th>ID</th>
</tr>";
foreach($submission as $row) {
echo "<tr>";
echo "<td>".$row->id."</td>";
echo "</tr>";
}
echo "</table>";
echo "<a id='export' href='?export=true'>Export Submissions as CSV</a>";
}
function submissions_export() {
global $wpdb;
$qry = array();
$qry[] = "SELECT * FROM wp_submissions";
$result = $wpdb->get_results(implode(" ", $qry), ARRAY_A);
if ($wpdb->num_rows > 0) {
$date = new DateTime();
$ts = $date->format("Y-m-d-G-i-s");
$filename = "submissions-$ts.csv";
header('Content-Type:text/csv');
header('Content-Disposition:attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
$hrow = $result[0];
fputcsv($fp, array_keys($hrow));
foreach ($result as $data) {
fputcsv($fp, $data);
}
fclose($fp);
}
}
if (ob_get_contents()) ob_end_clean();
if (isset($_GET['export'])) {
submissions_export();
}
错误来自此行:
fputcsv($fp, array_keys($hrow));
我查找了其他一些类似的问题,这似乎与空格有关,但是我不确定问题的根源。我从这些问题中尝试了几个答案,但是没有运气。