roughie Posted November 5, 2009 Share Posted November 5, 2009 In my code below, I write the first line, write intermediate lines, then write the last line. I want to skip a line after writing the first, and only the first, line. But - putting the "\n" after the first write causes all subsequent writes to also skip a line - something I do not want to happen, even though those fwrites do not have the "\n" in their syntax. Why does the first write's skip action carry into the rest of the fwrites, and how, then, do I get that first skip executed without influencing the rest? <?php $file = fopen("./readArray.php","r"); $wfile = fopen("./writeArray.txt", "w"); fwrite($wfile, "var jsArray = [\n"); while(! feof($file)) { $phpLine = fgets($file); fwrite($wfile, $phpLine); } fclose($file); fwrite($wfile, "]"); fclose($wfile); ?> If I change the first fwrite statement to fwrite($wfile, "var jsArray = ["); the writes get written each on their own line, as I want it. But, then, how do I skip only after the first fwrite? Thank you Quote Link to comment https://forums.phpfreaks.com/topic/180434-fwrite-why-is-it-skipping-lines/ Share on other sites More sharing options...
abazoskib Posted November 5, 2009 Share Posted November 5, 2009 use a simple counter <?php $count=0; while(! feof($file)) { $phpLine = fgets($file); fwrite($wfile, $phpLine); if($count==0) fwrite($wfile, "\n"); $count++; } Quote Link to comment https://forums.phpfreaks.com/topic/180434-fwrite-why-is-it-skipping-lines/#findComment-951921 Share on other sites More sharing options...
DavidAM Posted November 5, 2009 Share Posted November 5, 2009 The PHP manual for fgets() (http://us2.php.net/manual/en/function.fgets.php) says: Reading ends when length - 1 bytes have been read, on a newline (which is included in the return value), or on EOF (whichever comes first) If your input file has newlines, then they are in the $phpLine after you read the file, and are being written to the new file. You can get rid of them by using one of the trim() functions either on the read ... $phpLine = trim(fgets($file)); or on the write ... fwrite($wfile, trim($phpLine)); Quote Link to comment https://forums.phpfreaks.com/topic/180434-fwrite-why-is-it-skipping-lines/#findComment-951929 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.