Yes, i know this type of things are written many times. But my approach to it is for the IMAP protocol later. This is the 1st step to start from.

Suppose that $datatrim[0] is an array holding data from a file/mail/variable/database field etc. One can change it to the desired variable like from database field:

$datatrim = $row->data;

Use trim function to remove white spaces.

// Remove un wanted white spaces
$datatrim = trim($datamain[0]);
// Filename as datetime
$filename = date('dmYHis');
// Locaton to store the file
$filestore = "/var/www/html/test/"; 

// Check if $datatrim in not null(empty)
if($datatrim != '') { 
  // Open a file to write to it
  $fp=fopen($filestore.$filename, "w+") or die("can't open file");
  // Write into the file
  fwrite($fp, $datatrim);
  // Close the function

else {
  echo "Nothing to process!";

More about fwrite from

Happy coding!