adamgonge Posted March 6, 2014 Share Posted March 6, 2014 (edited) so i have a series of problems ive been working on and the last one is giving me problems. I have a script that reads a text file does some stuff with it and then displays it. that all works just fine now i have to add a fwrite to a external text file. basically the fget brings it in does some calculations and displays them line by line, I need to do the the same with fwrite but all it will do is write from the first line. heres my code <?php $fp =fopen("sales.csv", "r"); if(!$fp){ echo "could not open the file!"; exit(); } echo "<h2>Display Monthly Sales: "."</h2><br/>"; displayData($fp); function displayData($fp){ //define an array to store data while(!feof($fp)){ // read the current line $info = fgetcsv($fp, 250, ','); // add dataa only if data is nonempty if ($info[0] !=""){ // read the date into a variable $month = $info[0]; $sales =$info[1]; $rent =$info[2]; $wages =$info[3]; $supplies =$info[4]; }// end if // echo"<b>Month: </b> ".$month.",<b> Sales: </b> ".$sales."<b> Rent </b>".$rent."<b>Wages:</b>".$wages."<b>Supplies:</b>".$supplies."<br/>\n"; echo"<b>Month: Rent: Sales: Wages: Supplies: </b>"."<br/>\n"; echo "<b>".$month."</b>"." ".$sales." ".$rent." ".$wages." ".$supplies."<br/>\n"; echo "<br/>\n"; $fw = fopen("problem4.txt", "w"); $total_cost=$rent+$wages+$supplies; $operating_income = $sales-$total_cost; $net_income= $operating_income*.60; // use fwrite() to write data // syntax: fwrite('file_pointer, "string"); fwrite($fw, "Month: Sales: Total Cost: Operating Income: Net Income:"."\n"); fwrite($fw, $month." ".$sales." ".$total_cost." ".$operating_income." ".$net_income."\n" ); }//end while } ?> Edited March 6, 2014 by Ch0cu3r Quote Link to comment Share on other sites More sharing options...
Ch0cu3r Posted March 6, 2014 Share Posted March 6, 2014 The problem is here $fw = fopen("problem4.txt", "w"); Mode w will overwrite what was previously written to that file. The mode you'll want use would be a, so it'll append to what is currently written to that file. I'd do not recommend using fopen whilst within the while loop. Instead I'd open file just before it $fw = fopen("problem4.txt", "a"); // open problem4.txt and append to what is currently written to it. while(!feof($fp)){ Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.