Search code examples
phpforeachfwrite

Foreach loop printing duplicate last entry with output to data file


I have a foreach loop which loops through to present html and store data to a data file. The issue (which has been raised before) is that the last alliteration of the foreach loop is duplicated. Using unset does not work, as it writes the data file from within the foreach loop! How can I fix this issue? I want to cut out the duplicate and maintain writing to the data file...

My code:

// Save data to a DAT file
$datafile = "datfile.dat";
$fh = fopen($datafile, 'w') or die("can't open file");

foreach($xml->DROP as $shipment) {
    $CONNOTE_ID = $shipment->HEADER->BILL_OF_LADING; // 20 CHARS
    $output = sprintf("%-20.20s", $CONNOTE_ID);
    echo $output;
    unset($shipment);
    fwrite($fh, $output);
}

$output .= "%%EOF";
fwrite($fh, $output);
echo "%%EOF";
fclose($fh);

XML:

<?xml version="1.0" encoding="UTF-8"?>
<ISHPMNT1>
<DROP>
<HEADER>
  <BILL_OF_LADING>VW038687030000006</BILL_OF_LADING>
</HEADER>
</DROP>
</ISHPMNT1>

Solution

  • The issue resided with my understanding to how fwrite works. I was writing the last foreach 'output' variable twice, with the second adding %%EOF hence why it seemed like a duplicate sent through by the foreach loop.

    Fixed coding section:

    echo $output;
    fwrite($fh, $output);
    }
    fwrite($fh, "%%EOF");
    

    thanks to everyone who tried to help! Much appreciated