How can PHP variables with line breaks be properly formatted for HTML output?
When PHP variables with line breaks are echoed directly into HTML output, the line breaks may not be displayed as intended. To properly format PHP variables with line breaks for HTML output, you can use the nl2br() function in PHP. This function converts newlines in a string to HTML line breaks (<br> tags), allowing the line breaks to be displayed correctly in the HTML output.
<?php
// PHP variable with line breaks
$text = "Hello\nWorld";
// Format the variable for HTML output
$formatted_text = nl2br($text);
// Output the formatted text
echo $formatted_text;
?>
Keywords
Related Questions
- What is the common error message "Some data has already been output to browser, can't send PDF file" in FPDF output and how can it be resolved in PHP?
- What are some recommended methods for storing and retrieving data in PHP?
- What best practices should be followed when creating functions for specific user roles in PHP applications?