How to write quotation marks to a .txt file using fwrite

2.1k Views Asked by At

I have an html form where users can submit data. When they submit I am taking that data and writing it to a .txt file. I am having trouble adding quotation marks around my data. I need it to do the following when it writes to the txt file.

$name = $_POST['user'];

$data= "$name"

var Name="$data",

So if he user entered John on the form, I would need it to read: var Name="John",

On my data form. Any help is appreciated. I have tried addslashes, but can't seem to get that to work correctly either.

2

There are 2 best solutions below

0
On

try this:

$name = $_POST['user'];
$file_line = 'var Name="'.$name.'",';
fwrite($fh, $file_line);
0
On

There are quirks in programming that seem strange, but in particular the one preventing you from doing this is the fact that you are not treating the quotation marks (") as strings. Php is interpreting this:

$data = "$name";

As a request to turn $name into a string and store it inside of $data. What you want is to wrap the quotation marks with single quotations, so that php will turn them into a string. Then you concatenate (with the concatenation operator, the period (.) ) those with your $name variable, like so:

$data = '"'.$name.'"';

$data now holds the value: "John". Finally, for the actual string you want to write, you would concatenate your new variable with the 'var Name=' part:

$string = 'var Name='.$data;

So the value of $string now holds the string:

var Name="John"

Which is exactly what you want.