Brad Daniels
0
Q:

php write to file

$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
fwrite($myfile, "Content to write to file");
fclose($myfile);
3

 <?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
 
5
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);
4
// LOCK_EX will prevent anyone else writing to the file at the same time
// PHP_EOL will add linebreak after each line
$txt = "data-to-add";
$myfile = file_put_contents('logs.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);

// Second option is this
$myfile = fopen("logs.txt", "a") or die("Unable to open file!");
$txt = "user id date";
fwrite($myfile, "\n". $txt);
fclose($myfile);
2
$data[] = $_POST['data'];

$inp = file_get_contents('results.json');
$tempArray = json_decode($inp);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents('results.json', $jsonData);
2
<?php
$myfile = fopen("file_name.txt", "w") or die("Unable to open file!");
$txt = "Hello world\n";
fwrite($myfile, $txt);
$txt = " Php.\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
1
file_put_contents ($filename, $data, $flags = 0, $context = null): int
3

<?php

echo file_put_contents("test.txt","Hello World. Testing!");

?> 
 
0

New to Communities?

Join the community