jbwebdesign Posted April 27, 2009 Report Posted April 27, 2009 hello, I am trying to write a script that will allow me to export a loop onto a text file. The script seems to work fine but it doesn't want to export the loop itself. what happens is that it exports 2 numbers and not the whole 10 numbers that i want...... does anyone know how i can fix this?? //============WRITE THE FILES=================== //zero $zero = 0; //my prefix $prefix = "123456789"; $myFile = $prefix . "-0000-0249" . ".txt"; $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = $prefix . $zero . "000" . "\r\n"; fwrite($fh, $stringData); while($count<=8){ $stringData = $prefix . "000" . ++$count . "\r\n"; } fwrite($fh, $stringData); fclose($fh); //=============================================== Quote
jlhaslip Posted April 27, 2009 Report Posted April 27, 2009 (edited) The basic error was solved by moving the fwrite inside the while loop. Echos to the screen for debugging purposes. Check the comments re: $count Also, set permissions for the file to be written to //============WRITE THE FILES=================== //zero $zero = 0; //my prefix $prefix = "123456789"; $myFile = $prefix . "-0000-0249" . ".txt"; $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = $prefix . $zero . "000" . "\r\n"; fwrite($fh, $stringData); echo '' . $myFile . ' Should contain:'; // debug echo $count = 0; // adjust to suit - good programming suggests setting the value before using it while($count$stringData = $prefix . "000" . $count++ . "\r\n"; // $count++ and ++$count are different - check the results using each // ++$count adds 1 before using the value // $count++ adds 1 after using the value echo $stringData . ' '; // debug echo fwrite($fh, $stringData); // notice that the fwrite is now inside the while loop??? } // end while loop fclose($fh); //=============================================== ?> Edited April 27, 2009 by jlhaslip Quote
BeeDev Posted April 30, 2009 Report Posted April 30, 2009 Or you can also just include a dot in front of the equal sign on your original code. Result would be the same ... while($count<=8){ $stringData .= $prefix . "000" . ++$count . "\r\n"; //Notice the . (dot) in front of the equal sign } ... .= is basically a shortcut. In your case it just means: $stringData = $stringData . $prefix ..... and so on So $stringData get a new value ADDED to it, instead of taking a new value on each iteration. And instead of writing to a file everytime in the loop, it would be better for performance if your code wrote to a file only ONCE at the end of the loop. Quote
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.
Note: Your post will require moderator approval before it will be visible.