Search code examples
phphtmlfwriteoutput-buffering

PHP best way to output certain data to text?


Ok, so I have a form that takes a username and a code. This is then passed to php for processing. I am not super php saavy, so I want to be able to take a specific portion of the out put and write it to a text file, this form would be used over and over, and I want the text to be appended to the file. As you can see from the output I'm looking to capture, it's basically writing to some code that will be used for usernames in a css. So here is what I have...

  1. The HTML Form

<html><body>
<h4>Codes Form</h4>
<form action="codes.php" method="post"> 
Username: <input name="Username" type="text" />
Usercode: <input name="Usercode" type="text" /> 
<input type="submit" value="Post It!" />
</form>
</body></html>
  1. The PHP


--><html><body> <?php $Usercode = $_POST['Usercode']; $Username = $_POST['Username'];

echo "You have recorded the following in our system ". $Username . " " . $Usercode . ".<br />"; echo "Thanks for contributing!";

echo .author[href$="/$Username"]:after { echo content: "($Usercode)" echo }

?> </body></html>

All that I would like to be written to the text file would be this portion..


--> .author[href$="/$Username"]:after { content: "($Usercode)" }

Basically, the text file would have line after line of that exact same code, but with different usernames and usercodes. Hopefully, the variable $Usercode and $Username can also be captured and written into the output in the manner that I have it written. I'm just baffled by output buffering in php and clean and flush etc, and fwrite doesn't seem to be able to write without wiping a file clean each time it writes to it. I may be wrong of course. Anyone care to help?


Solution

  • Try this:

    <?php
    $output = "--> .author[href=$Username]:after { \n"
           ."content: ($Usercode)\n"
           ."}";
    $fp = fopen($file, 'a');
    fwrite($fp, $output);
    fwrite($fp, "\n");
    fclose($fp);
    ?>
    

    The flag a will open already a text file and place the pointer to the end of file, so this will not overwrite your already file, more information in fopen.