Jump to content

Fwrite help stuck for a while now!


adamgonge

Recommended Posts

 

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

Link to comment
https://forums.phpfreaks.com/topic/286747-fwrite-help-stuck-for-a-while-now/
Share on other sites

The problem is here

$fw = fopen("problem4.txt", "w");

Mode 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)){

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.