2013-10-17 201 views
0

我試圖從XML文件中獲取數據,然後將其寫入CSV文件。在生成的文件中,它在每條記錄後放置了很多空行。如何在php中刪除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"; 
     } 
    } 
} 
?> 

回答

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); 
} 
?> 
+0

感謝答覆,但它給予相同的輸出 – Aanshi

+0

我thnk somthng是錯在那裏loop.eg中的foreach找到3個記錄。 。然後爲第一條記錄FOR循環執行4次。所以對於第一個記錄只有一個記錄,所以..它會留下3空白行嗎?我只是假設不確定 – Aanshi

+0

'if($ key <$ array_count-1)' –