0

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 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Fail, dude... it bugs me when people peddle false information with such certitude. : /
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.
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.
Just for the record, was the browser the problem?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.