views:

564

answers:

2

Hi All

I am building a JS page dynamically with php using .htaccss to make .php into .js

All works well apart from the output of the JS.

IE

$data = array('one', 'two');

foreach($data as $d){
    echo "document.write('This is a test for array item ".$d."'); \r\n";
}

Problem is it outputs it all on one line ie

document.write('This is a test for array one');document.write('This is a test for array two');

No matter what I have tried I cant get it over 2 lines.

Any ideas ?

+2  A: 

Edit: It looks like I misunderstood the question - he was having trouble with newlines in his JS, not his final HTML.


Your JavaScript is coming out on separate lines because of the "\r\n" at the end of the string, but then you're outputting plain text into your HTML document. HTML does not break lines unless you're in a pre-formatted block (like "<pre>") or you give it an explicit break (like "<br>").

You probably want your code to look like this:

foreach($data as $d){
  echo "document.write('This is a test for array item ".$d."<br>'); \r\n";
}

Just be very careful of your data - inserting random strings into your HTML is a fast way to get security holes.

Neall
Fail, dude... it bugs me when people peddle false information with such certitude. : /
Hexagon Theory
Im not actually worried about the inner content new line as that would ust be html like you have said. Its getting the document.write on to new lines.
Lee
It looks like I misunderstood the question. I ran the exact code you posted, and the document.writes come out on separate lines. Are you sure you don't have some sort of JavaScript compression layer on your web server? Are you sure that your web browser isn't munging the code for you? Try downloading the JS with wget or some other command-line utility.
Neall
ok My Bad !!!!. I cant believe I was being so thick.Thanks for you time
Lee
Just for the record, was the browser the problem?
Neall
A: 

Heh, actually, I think if you view the source of the generated file you will find that the line breaks are indeed there. : )

Hexagon Theory