XML到CSV,只获得一行?

时间:2010-10-03 02:58:04

标签: php xml csv

我在使用这个XML到CSV脚本时遇到了麻烦..当我删除标题时,所有内容都回声但是我只得到了CSV文件的最后一行。我关闭了E_NOTICE警告,因为并非所有delivery-requests都有customer-ref1,而且我不确定如何测试此isset()似乎不起作用。我怀疑它可能是问题的一部分..无论如何,这是代码:

<?php
error_reporting(E_ALL ^ E_NOTICE);
if (isset($_FILES) && isset($_POST['submit'])) {
     $page = file_get_contents($_FILES['import']['tmp_name']);
     $doc = new DOMDocument();
     $doc->loadXML($page); 
     $delivery_requests = $doc->getElementsByTagName("delivery-request");
     $count=0;                             
     foreach ($delivery_requests as $delivery_request) {
         $count++;
         $product_id = $delivery_request->getElementsByTagName("product-id")->item(0)->nodeValue;
         $weight = $delivery_request->getElementsByTagName("weight")->item(0)->nodeValue;
         $customer_ref1 = $delivery_request->getElementsByTagName("customer-ref1")->item(0)->nodeValue;
         $pre_tax_amount = $delivery_request->getElementsByTagName("pre-tax-amount")->item(0)->nodeValue;
         $item_id = $delivery_request->getElementsByTagName("pre-tax-amount")->item(0)->nodeValue;
         $mailing_date = $delivery_request->getElementsByTagName("mailing-date")->item(0)->nodeValue;
         ob_clean();
         header("Cache-Control: public");
         header("Content-Description: File Transfer");
         header("Content-Disposition: attachment; filename=export.csv");
         header("Content-Type: application/octet-stream");
         header("Content-Transfer-Encoding: binary");
         echo $product_id . "," . $weight . "," . $customer_ref1 . "," . $pre_tax_amount . "," . $item_id . "," . $mailing_date . "\n";     
     }                                               
     exit;
} else { 
?>
    <h2>Import XML<h2>
    <form action="import.php" method="post" enctype="multipart/form-data">
        <input type="file" name="import">
        <input type="submit" name="submit" value="Import">
        <input type="button" value="Cancel" onclick="window.location='import.php'">
    </form>
<?php
}
?>

一如既往 - 谢谢!

1 个答案:

答案 0 :(得分:1)

您需要将输出缓冲区调用和标头调用移出foreach循环。

如果移动

,它是否按预期工作
ob_clean();
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=export.csv");
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: binary");

走出循环?丢失的customer-ref1怎么样?