The solution is to use a couple of PHP string handling functions.
One to convert newlines to strings: nl2br() Another to convert special characters to their corresponding codes: htmlentities()
The two functions receive the string and return the same altered string.
To use it, suppose you have a string in a $string variable and you want to convert it to HTML and print it to the screen:
echo nl2br(htmlentities($string));