Jump to content

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/180434-fwrite-why-is-it-skipping-lines/
Share on other sites

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));

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.