Newline and Other Special Characters Both of the below examples make use of the newline character (\n) to signify the end of the current line and the beginning of a new one.
The newline is used as follows:
Code:
echo "PHP is cool,\nawesome,\nand great.";
Output:
PHP is cool, awesome, and great.
Notice: the line break occurs in the output where ever the \n occurs in the string in the echo statement. However, a \n will not produce a newline when the HTML document is displayed in a web browser. This is because the PHP engine does not render the script. Instead, the PHP engine outputs HTML code, which is subsequently rendered by the web browser. The linebreak \n in the PHP script becomes HTML whitespace, which is skipped when the web browser renders it (much like the whitespace in a PHP script is skipped when the PHP engine generates HTML). This does not mean that the \n operator is useless; it can be used to add whitespace to your HTML, so if someone views the HTML generated by your PHP script they'll have an easier time reading it.
In order to insert a line-break that will be rendered by a web browser, you must instead use the <br /> tag to break a line.
Therefore the statement above would be altered like so:
echo 'PHP is cool,<br />awesome<br />and great.';
The function nl2br() is available to automatically convert newlines in a string to <br /> tags.
The string must be passed through the function, and then reassigned:
Additionally, the PHP output (HTML source code) generated by the above example includes linebreaks.
Other special characters include the ASCII NUL (\0) - used for padding binary files, tab (\t) - used to display a standard tab, and return (\r) - signifying a carriage return. Again, these characters do not change the rendering of your HTML since they add whitespace to the HTML source. In order to have tabs and carriage returns rendered in the final web page, &tab; should be used for tabs and <br /> should be used for a carriage return.