php - PHP Fputcsv标头未显示
问题描述
我正在尝试使用 magento 的产品在 php 中创建一个 csv,但我的标题没有显示在 csv 文件中,只是产品。
如果我将标题的 fputcsv 放在 foreach 中,它会显示标题,然后是一个产品,然后是标题,然后是另一个产品,依此类推......
##### Print product data ####################################################
$headings = ['category', 'manufacturer', 'productid', 'identifier', 'name', 'description', 'product_url', 'image_url', 'price','show_product', 'availability', 'delivery_cost'];
$fh = fopen('php://output', 'w');
ob_start();
fputcsv($fh, $headings);
foreach($ALL_PRODS as $productId) {
// If we've sent this one, skip the rest - this is to ensure that we do not get duplicate products
if (@$already_sent[$productId] == 1) continue;
$PRODUCT = array();
$PRODUCT = smfeed_get_product_details($productId);
if ($PRODUCT['show_product'] == 1 ) {
fputcsv($fh, $PRODUCT);
$string = ob_get_clean();
$filename = 'csv_' . date('Ymd') . '_' . date('His');
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$filename.csv\";");
header("Content-Transfer-Encoding: binary");
$prod_count ++;
// Debuging
if (isset($_GET['debug'])) {
$cnt_prod ++;
if (@$_GET['stats'] == "off") {
}
else {
echo $cnt_prod . ".";
echo "\t" . number_format(microtime(true) - $time, 3) . "s \n";
$time = microtime(true);
echo "\t" . number_format(memory_get_usage()/1048576, 3) . "Mb\n";
}
}
// Limit displayed products
if ($limit > 0 && $prod_count >= $limit && !isset($_GET['pg'])) {
// Debuging
if (isset($_GET['debug'])) {
echo "\n" . $cnt_prod . "products displayed \n";
echo "\npage loaded in " . number_format(microtime(true) - $time_start, 3) . "s \n";
echo number_format(memory_get_usage()/1048576, 3) . "Mb\n";
}
exit;
}
}
$already_sent[$productId] = 1;
}
exit($string);
解决方案
ob_start();
开始输出缓冲。
缓冲区包含标题行。
第一个产品输出完成后,输出缓冲结束于ob_get_clean();
由于$string = ob_get_clean();
在循环中调用了赋值,它的内容被false
值重写(因为之前缓冲已经结束),因此 finalexit($string);
不会输出任何东西。
您的代码中还有许多其他问题。例如,将为循环中的每个项目反复设置 HTTP 标头。
推荐阅读
- html - Make a div with buttons inline
- julia - Julia notebook in win64
- ruby-on-rails - Why do I suddenly get a blank screen with Rails on localhost?
- signalr - Signalr Core 将用户添加到组 OnConnected 安全性
- python - Balls are catched by bounds and they stick together (incorrect algorithm in draw method)
- angular - 如何减少 Angular 5 中的代码行数
- dns - 为什么 Mailgun 需要大量信息进行域验证?
- powershell - 如何使powershell在按下标签后显示建议列表?
- java - Mac Eclipse 创建 Android - “在项目上运行构建器 'Android 资源管理器' 时出错”
- php - CodeIgniter: Trying to load the option values from database table based on the selection of first select option