remove lines from DAT file
Posted: Thu Dec 04, 2008 11:27 am
Hi All,
I have the following code which adds items into a DAT file, works ok but writes a new line if more than one item is entered so the file ends up odd i.e.
item1
item1
empty line
item1
empty line
item2
empty line
line1
empty line
Any know now to prevent this? I could do with some sort of code that will strip the file of blank lines after its finshed writing.
I have the following code which adds items into a DAT file, works ok but writes a new line if more than one item is entered so the file ends up odd i.e.
item1
item1
empty line
item1
empty line
item2
empty line
line1
empty line
Any know now to prevent this? I could do with some sort of code that will strip the file of blank lines after its finshed writing.
Code: Select all
<html>
<head>
<title>ebusiness</title>
</head>
<body>
<h1>Your Purchase is confirmed</h1>
<p>Thank you</p>
<table border=1>
<?php
//check the file for purchases can be opened
$myFile = 'purchases.dat';
$fh = fopen($myFile, 'a') or die("Can't open file\n");
$total=0;
//check the items file can be opened
if (!($lines = file('items.dat')))
{ echo 'ERROR: Unable to open file! </body></html>'; exit;}
foreach($_POST as $varname=> $varvalue) {
//list each item in array, using the separator '|'
foreach ($lines as $theline) {
list($id, $name, $description, $price, $image) = split('\|', $theline);
if ($id==$varname)
{ echo "
<tr>
<td> $id </td>
<td> $name </td>
<td> $description </td>
<td> $price <input type='hidden' name='$id'></td>
<td><img src='$image' width='50' height='50'></td>
</tr> ";
$total=$total+$price;
//create an entry for append-write to file
$content = $id ."|". $name ."|". $description ."|". $price ."|". $image ."\n";
if (!(fwrite($fh , $content)))
{ echo "Can't write to ($myFile)\n</p>"; exit; }
}
}
}
echo " <tr> <td> </td>
<td align='right'> Total: </td>
<td> £$total </td> </tr>";
?>
</table>
<p><a href="home.php">Click to go home<a/></p>
</body>
</html>