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
https://forums.phpfreaks.com/topic/60267-opposite-of-file/
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
https://forums.phpfreaks.com/topic/60267-opposite-of-file/#findComment-299791
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
https://forums.phpfreaks.com/topic/60267-opposite-of-file/#findComment-299793
Share on other sites

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.