Jump to content

Append to new line in text file


ajd344

Recommended Posts

Hey, I'm appending information to a regular text file (not html). I need to put a new line in for each entry added on, not just add on to it. I tried \n, but it didnt work, it just made a weird square at the end.

 

Any ideas?

Thanks

Link to comment
Share on other sites

Well, I'm trying to figure this out, but I cant. Here, maybe you spot something in my code:

 

$myFile = "data/data.txt";

$fh = fopen($myFile, 'a') or die("error");

fwrite($fh, "$out");

fclose($fh);

 

The output is like this: ([] being a weird square)

entryone[]entrytwo

 

When I copy and paste that square, it makes a new line. Huh.

 

Thanks

Link to comment
Share on other sites

From the manual, with little modification to fit your variable names etc:

<?php
$myFile = 'data/data.txt';
$out = "Add this to the file\n";

$handle = fopen($myFile, 'a');

// Let's make sure the file exists and is writable first.
if (is_writable($myFile)) {

    // In our example we're opening $filename in append mode.
    // The file pointer is at the bottom of the file hence
    // that's where $out will go when we fwrite() it.
    if (!$handle = fopen($myFile, 'a')) {
         echo "Cannot open file ($myFile)";
         exit;
    }

    // Write $out to our opened file.
    if (fwrite($handle, $out) === FALSE) {
        echo "Cannot write to file ($myFile)";
        exit;
    }

    echo "Success, wrote ($out) to file ($myFile)";

    fclose($handle);

} else {
    echo "The file $myFile is not writable";
}
?> 

 

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.