Complete website in Rs. 5,000 with Free Hosting & Domain. Offer ends in  00:00:00
Back to Blog

How to Edit/Update TEXT, JSON and CSV files with PHP

Create, readd, update and delete text, json and csv files with PHP

Jan 7, 2023 Updated: Jan 7, 2023

Create files with PHP

For more ways of opening a file with fopen(), check the php documentation here.

// get path of current folder or use get_stylesheet_directory() in WordPress
$folder = getcwd();
$file_path = $folder . '/my-file.txt';
$content = 'some text here';
// open the file for writing only, create if file does not exist
$fp = fopen($file_path, 'w');
fwrite($fp,$content);
fclose($fp);

If you just want to create an empty file, then you can use touch(). You can provide the path in any way you prefer or you can directly give the file name.

touch(__DIR__ . '/my-file.txt');
touch(getcwd() . '/my-file.txt');
touch('my-file.txt');

Editing TEXT files

You can pretty print array in text files for use as a looger.

$file_path = getcwd() . '/my-file.txt';
$fp = fopen($file_path, 'a'); // open in write only append mode
fwrite($fp, print_r( array(
    'user_email' => $user_email,
    'user_id' => $user_id,
), TRUE) );
fclose($fp);

Delete files with PHP

Process of deleting file is same for all. Just like like touch(), you can delete file with it’s full path or just the file name.

unlink(__DIR__ . '/my-file.txt');
unlink(getcwd() . '/my-file.json');
unlink('my-file.csv');
Contact

Got A Question For Us?

Feel free to ask anything directly on call or fill the form and we will contact back within few hours.