remove lines from DAT file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
phpPain
Forum Newbie
Posts: 10
Joined: Mon Nov 24, 2008 6:14 am

remove lines from DAT file

Post by phpPain »

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.

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>
 
 
 
 
 
User avatar
novice4eva
Forum Contributor
Posts: 327
Joined: Thu Mar 29, 2007 3:48 am
Location: Nepal

Re: remove lines from DAT file

Post by novice4eva »

Code: Select all

$content = $id ."|". $name ."|". $description ."|". $price ."|". $image;
Post Reply