Search code examples
phpfile-iospecial-characters

PHP saving a string to a file "as is" including eg \n


I have a variable which contains a string, I don't know what the string might be but it could contain special characters.

I'd like to output that into a text file "as is". So if there is for example a string "my string\n" I want the text file to show exactly that and not interpret the \n as a line feed / new line.


Solution

  • The answer for "\n" is to replace any potential new line character with the literal characters. str_replace("\n", '\n', $myString)

    Not sure what the general case may be though for other potential special characters.