Michael Emerson
Michael Emerson

Reputation: 1813

Newlines in javascript within a PHP variable

I've written some PHP which encases some javascript within a PHP variable, like so:

$js .= 'response['.$x.'] = FinanceDetails("'.$finance_code.'",' . $cart_value . ','.$minimum_deposit.','.$total_cost.');';

But this can be repeated up to three times, and then it's injected between <script> tags and I'd like it to show like so:

response[0] = FinanceDetails("ONIF12",290.00,10,1500);
response[1] = FinanceDetails("ONIF6",290.00,10,1500);
...

But currently it shows in one long string as there are no line breaks. I've tried adding \n and \r as well as \n\r together at the end of the $js value but I just keep getting an Illegal character error - how would I implement a new line / line break in this situation?

Upvotes: 2

Views: 46

Answers (1)

tobspr
tobspr

Reputation: 8386

You have to use the "" quotation marks instead of '' to be able to print out newlines. For example:

$js .= 'response['.$x.'] = FinanceDetails("'.$finance_code.'",' . $cart_value . ','.$minimum_deposit.','.$total_cost.');' . "\n";

Otherwise PHP does not parse the newline and your code ends up with a "\n" in it.

Upvotes: 2

Related Questions