I’m creating a PHP class that can write an array of strings to a file, which is then read line-by-line.
I need to make sure that special characters like ‘\n’ get written to the file literally, rather than messing with the format of the file. This only seems to work when using single-quoted strings.
<?php
//EXAMPLE ONE - DOUBLE QUOTES ----------
$user_input = "This is the \n input.";
file_put_contents("input.txt", $user_input);
//OUTPUT
//
//This is the
// input.
//
//EXAMPLE TWO - SINGLE QUOTES ----------
$user_input = 'This is the \n input.';
file_put_contents("input.txt", $user_input);
//OUTPUT
//
//This is the \n input.
//
?>
How can I achieve the output of example two even if $user_input is in double quotes?
It is happening because \n is cosidering as new line charcter here, so you escape the character. change it to \\n