【问题标题】:PHP Fputcsv header not showingPHP Fputcsv标头未显示
【发布时间】:2020-01-10 11:14:51
【问题描述】:

我正在尝试使用 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);

【问题讨论】:

    标签: php magento


    【解决方案1】:

    ob_start(); 开始输出缓冲。

    缓冲区包含标题行。

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

    由于在循环中调用$string = ob_get_clean(); 赋值,其内容被false 值重写(因为之前缓冲已结束)因此最终exit($string); 不输出任何内容。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-08
      • 1970-01-01
      • 1970-01-01
      • 2014-02-18
      • 2016-12-30
      相关资源
      最近更新 更多