如何在php中删除CSV文件中的空白行

时间:2013-10-17 05:47:26

标签: php

我试图从xml文件中获取数据,然后将其写入CSV文件。在生成的文件中,每条记录后都放了这么多空行。

<?php

header("Content-Type: application/vnd.ms-excel");
header("Content-disposition: attachment; filename=spreadsheet.xls");
$url = 'test.xml'; // xml file location with file name
if (file_exists($url)) {
    $xml = simplexml_load_file($url);
    echo 'item_no' . "\t" . 'description' . "\t" . 'price' . "\t" . 'base_qty' . "\t" . 'var_qty' . "\t" . 'base_price_1' . "\t\n";
    foreach ($xml->record as $books) {
        $array_count = count($books);
        for ($key = 0; $key < $array_count; $key++) {
            echo $books->item_no[$key]."\t" . $books->description[$key]."\t" . $books- >price[$key]."\t" . $books->base_qty[$key] . "\t" . $books->var_qty[$key] . "\t" . $books->base_price_1[$key] . "\t" . "\n";
        }
    }
}
?>

1 个答案:

答案 0 :(得分:2)

确保最后一条记录中未打印\n

<?php

header("Content-Type: application/vnd.ms-excel");
header("Content-disposition: attachment; filename=spreadsheet.xls");
$url = 'test.xml'; // xml file location with file name
$output = "";
if (file_exists($url)) {
    $xml = simplexml_load_file($url);
    $output.= 'item_no' . "\t" . 'description' . "\t" . 'price' . "\t" . 'base_qty' . "\t" . 'var_qty' . "\t" . 'base_price_1' . "\t\n";
    foreach ($xml->record as $books) {
        $array_count = count($books);
        for ($key = 0; $key < $array_count; $key++) {
            $output.= $books->item_no[$key]."\t" . $books->description[$key]."\t" . $books- >price[$key]."\t" . $books->base_qty[$key] . "\t" . $books->var_qty[$key] . "\t" . $books->base_price_1[$key] . "\t" . "\n";
        }
    }
    echo rtrim($output);
}
?>