If you are creating the File on the fly and you do not want to save it on the server but instead download it on client computer after an action is triggered from client side e.g. like a button click from a User Web Browser, you can write the PHP code as follows;
$dataToWriteToFile = "This Text has been saved in this Text File and Downloaded for you to View !";
$fileName = "TxtFilename.txt";
$file = fopen($fileName,"wb");
header("Content-disposition: attachment; filename=$fileName");
DISCLAIMER: It will not work for those intending to write a file to server for archiving but for anyone else creating a file on the fly for purpose of making their client users download it to their web browsers it may suffice for that purpose.
I was about to talk to my client to request them to allow the Apache user to add more rights to the Apache user (as is suggested by previous answers here and other related Questions on internet) to allow writing files to the folder where their server web pages are served from. I am almost certain this would have been an uphill task for them to agree to but luckily the above code worked for me.