tags:

views:

30

answers:

1

I'm having trouble with this XML to CSV Script.. when I remove the headers everything echos but with them I only get the last line of the CSV file. I turned off E_NOTICE warnings as not all of the delivery-requests have customer-ref1 and I'm not sure how to test for this isset() doesn't seem to work. I suspect that it may be part of the issue.. anyways, here's the code:

<?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
}
?>

As always--Thanks!

+1  A: 

You need to move the output buffer call(s) and header calls out of your foreach loop.

Does it work as expected if you move

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");

out of the loop? How about the missing customer-ref1?

mbanzon
LOL.. I noticed that after I submitted the question
Mikey1980