Member Avatar for kirtan_thakkar

I want to add text string at the end of the text file. I used "a+" for it but it delete all the content and than enters text to it. So please help.

<script>
var text1 = "abc";
var text2 = "def";

document.write(text1 + text2);
</script>
Member Avatar for kirtan_thakkar

I want to add a text at the end of a file and code should be in php. Not in java.

I'm sorry. Was browsing both forums. Do you have your fopen/fwrite codes?

Just use dot (.)

<?php
 
  $text1 = "World";

  echo "Hello ".$text1; //The output will be Hello World

  $text2="Hello";

  echo $text2." World"; //The output will be Hello World
?>

I think he's writing into an external file. "a+" should be correct. So I hope he can provide us with the codes to debug.

$f = fopen( 'filename.txt', 'a' );
fwrite( $f, 'something' );
fclose( $f );
Member Avatar for kirtan_thakkar

Sorry guys.. I was unable to reply.. Now here is my code..

$file = "status.txt";
$f = fopen($file,"a+");
file_put_contents($file,$data);
fclose($f);

But it is removig all content of the file and than adding new contenet..

Hi,
Replace the 3rd line with the below code.

file_put_contents($file,$data,FILE_APPEND);

The third parameter need to be set in file_put_contents to append with existing data. otherwise it would overwrite the existing file contents. check the manual file-put-contents

Wrong code:

    $file = "status.txt";
    $f = fopen($file,"a+");
    // file_put_contents($file,$data); // This is doing ur file blank & then add the data
    fwrite($fh, $data); // This will append the string to the end of of the file
    fclose($f);



Working code


$myFile = "testing.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$string = "New String 1\n";
fwrite($fh, $string);
$string = "New String 2\n";
fwrite($fh, $string);
fclose($fh);

Prashant Patil

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.