How can i pass a string with multiple line to a javascript function?

Hi,

I have a variable in php
$test = “This is a string
It has multiple lines
there are three total” ;(Output from a text area) . I want to pass this variable to a javascript function

I have write this in my php file

<?php echo “<script language=javascript>convert(‘$test’);</script>”; ?>

but this makes an error “Unterminated string literal” How can i solve this issue ??

I think you can’t have line breaks in php string declarations.

This is true. You would have to specific a line break with the <br /> tag and keep the whole string on one line.

$test = "This is a string<br />It has multiple lines<br />There are three total";

Out of curiosity, what is the end goal here? I’m not sure it’s wise to mix server side scripting with javascript. Instead, I would use a PHP function to try to replicate the javascript function.

Also, what is the purpose of having a PHP variable with multiple lines?

(sorry for all the questions… I just think there may be an easier way to do what it is you’re trying to do).

This is always tricky. For simple line breaks, you can do this:

<?php
$test = "This is a string
It has multiple lines
there are three total";
$test = str_replace("\\r", "\\\\r", $test);
$test = str_replace("\
", "\\\
", $test);
echo $test;
// This is a string\\r\
It has multiple lines\\r\
there are three total
?>

On second thought, you should use a javascript framework such as jQuery. You can simply put the contents inside a (hidden) div and then read them back in your javascript. This is search engine friendly as well, if that matters. Search engines do not see strings inside javascript but inside html elements, yes.

If you still want a PHP solution, I just figured out a better solution:

<?php
$test = "This is a string
It has multiple lines
there are three total";
echo json_encode($test);
// "This is a string\\r\
It has multiple lines\\r\
there are three total"
// notice json_encode adds double quotes around the string
// it will add backslashes if necessary
?>