How can line breaks in PHP text be handled to prevent issues in JavaScript?

When outputting PHP text that contains line breaks to JavaScript, it is important to properly handle these line breaks to prevent syntax errors. One way to do this is by using the PHP function `json_encode()` to encode the text, which will automatically escape special characters like line breaks. This ensures that the text is properly formatted for JavaScript to interpret.

<?php
$text_with_line_breaks = "This is a text with\nline breaks.";
$encoded_text = json_encode($text_with_line_breaks);
echo "<script> var text = $encoded_text; </script>";
?>