Jump to content

Append to new line in text file


ajd344

Recommended Posts

Have you looked at fwrite() in the manual (http://www.php.net/manual/en/function.fwrite.php)? \n should work... did you enclose it in single quotes or double? It would only parse in double.

 

Edit:

http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single to further explain what I mean.

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

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";
}
?> 

 

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.