0

我正在尝试从 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";
        }
    }
}
?>
4

1 回答 1

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);
}
?>
于 2013-10-17T05:50:05.530 回答