首页 > 解决方案 > 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);

标签: phpmagento

解决方案


ob_start();开始输出缓冲。

缓冲区包含标题行。

第一个产品输出完成后,输出缓冲结束于ob_get_clean();

由于$string = ob_get_clean();在循环中调用了赋值,它的内容被false值重写(因为之前缓冲已经结束),因此 finalexit($string);不会输出任何东西。

您的代码中还有许多其他问题。例如,将为循环中的每个项目反复设置 HTTP 标头。


推荐阅读