Jump to content

Opposite of file()?


UncleRico

Recommended Posts

I am having troubles writing dynamic PHP files, the trouble is that new lines(\n, \r\n) aren't being written. 

 

The line by line format is important as when the file is read into a different function via file(), the array indexes have meanings.

 

Is there a function that is essentially the opposite of file(), one that would write each array index into its own line of a file?  Below is the code I am using, its doing everything I need it to do except put in line breaks.

 

Any help would be extremely appreciated!

 

function writeNewPR($fileName, $contentArray){

 

foreach($contentArray as $line){

$newPR = fopen($fileName, 'a');

fwrite($newPR, $line);

fwrite($newPR, '\r\n');

fclose($newPR); //closes file

}

 

 

 

}

Link to comment
Share on other sites

it's probably because you're inserting the literal strings, as opposed to the characters they represent.  a faster route is likely to implode() the array into one string and write it all at once, using the newline/return carriage characters as the glue:

 

function writeNewPR($fileName, $contentArray){

  $glue = chr(13).chr(10);
  $string_to_write = implode($glue, $contentArray);

  $newPR = fopen($fileName, 'w+');
  fwrite($newPR, $string_to_write);
  fclose($newPR);

}

 

note i've changed the fopen() mode, simply because you'll want to replace it with the whole chunk.

Link to comment
Share on other sites

Yeah, that function I posted is much less elegant that initially as a result of boiling it down to try to figure out where it was going wrong.  I found the solution, 5 mins after I posted, the problem was the single quotes around the new line chars, changed them to double quotes and it worked.  Typical stupid little thing...!  Thanks anyhow.

Link to comment
Share on other sites

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.