How can the nl2br function be used to preserve line breaks in PHP when retrieving data from a database?
When retrieving data from a database in PHP, line breaks are often stored as "\n" or "\r\n". When displaying this data on a webpage, these line breaks may not be rendered correctly. To preserve line breaks, you can use the nl2br function in PHP, which converts newline characters to HTML line breaks (<br>). Simply apply the nl2br function to the retrieved data before displaying it on the webpage.
// Retrieve data from the database
$data = "Hello\nWorld";
// Preserve line breaks using nl2br
$preserved_data = nl2br($data);
// Display the preserved data on the webpage
echo $preserved_data;
Keywords
Related Questions
- What are the key differences in syntax between assigning values to variables in PHP?
- How can one troubleshoot and resolve issues with initial character encoding settings, such as Latin1, when working with PHP and MySQL connections?
- In what scenarios is it necessary to use wrapper functions to call certain PHP functions, and what are the implications for variable function usage?