PJ Hile

Don’t worry, I’m from the Internet.

PJ Hile header image 2

Javascript strings over multiple lines from PHP

March 13th, 2008 · No Comments

I had a problem where I was defining javascript variables from php variables, and the php variables had multiple lines.

So, a function like this:
function SomeFunction() {
var variable = "<?php echo $variable; ?>";
}

was creating this:
function SomeFunction() {
var variable = "The first row.
The second row.
The third row
";
}

The fix was to replace all the ‘\n’ with ‘\\n’, so the literal string ‘\n’ is output instead of an actual line break.

Like so:
var variable = "<?php echo str_replace('\n', '\\n', $variable); ?>

Tags: Javascript · PHP

0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form below.

Leave a Comment