www.webdeveloper.com
Results 1 to 5 of 5

Thread: [RESOLVED] New line in .txt file

  1. #1
    Join Date
    Jan 2009
    Posts
    31

    resolved [RESOLVED] New line in .txt file

    Hi, I'm trying to write a string passed from a <textarea> through an ajax function to a txt file. I know that a newline is written in the textarea using \n, but in the text file using \r\n (I'm on Windows), so I used preg_replace() to replace any instance of \n with \r\n. When I send the string "I redid this file.\nIt now has two lines." to php, the text file shows:
    "I redid this file.\r\nIt now has two lines. ".
    When I commented out the preg_replace(), the text file showed:
    "I redid this file.It now has two lines."
    Here is the code I'm using. (I've verified that the newline character is being sent by checking the string sent using firebug)
    PHP Code:
    $file urldecode($_GET['file']);
    $text urldecode($_GET['text']);
    $text preg_replace("/\\n/""\\r\\n"$text);
    if(!
    is_file($file)){
        die(
    'There was a problem saving the file.  It may no longer exist.');
    }
    $handle fopen($file'w');
    if(
    fwrite($handle$text)){
        print 
    'The file was successfully saved.';
        print 
    $text;
    }
    else{
        die(
    'There was a problem saving the file.  It may be write-protected.');

    Any ideas?

  2. #2
    Join Date
    Jan 2009
    Posts
    3,346
    I know this is going to sound like a stupid question but if you open the file with notepad is it showing the content on multiple lines? If so are you only having trouble in the bowser? If so try putting <pre> tags around you echoed content.

  3. #3
    Join Date
    Jan 2009
    Posts
    31
    Like I said, the text file shows it all on one line with the "\r\n" literally shown when I open it with a text editor. The content comes from a textarea tag, which displays the content properly. The problem is only that the newlines are not written properly to the text file.

  4. #4
    Join Date
    Jan 2009
    Posts
    3,346
    Thats because you are escaping your \r\n as \\r\\n. This will make it show \r\n as text instead of a newline character. I just glanced over your post before and skipped the line where you showed the output in the text file somehow earlier. Sorry for that.

  5. #5
    Join Date
    Jan 2009
    Posts
    31
    Thank you very much. That makes a lot of sense now that I think about it.
    I guess I was stuck in the "passing a string from javascript to php" mindset as far as the escaping goes.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles