Is there a way to force a new line after php closing tag ?> when embedded among html?

Viewed 5637

I have been searching online with little success for a way to force php to output a newline after a closing php tag ?> so that my HTML will be rendered as I see it before its parsed by PHP so that it will look neat and tidy when viewing the html source code for a page.

I want to stop it from removing the newline and causing the next line from wrapping up and therefore ruining the format of the page. Is there a specific php.ini setting I can change to disable this behaviour?

All my code logic files have ?> removed from the end of them so I wont need to worry about them injecting extra newlines which is why I believe PHP was coded to strip the trailing new lines.

8 Answers

Richard is saying this:

Hello <? ?>
Jello

...after PHP-parsing becomes this:

 Hello Jello


I just add an extra newline manually, like this:

Hello <? ?>

Jello

...giving this:

Hello
Jello

You can try this:

echo "output \n";

or even this much less elegant technique:

echo "output
";

Please paste some example code snippet to get more specific help.

You can't always just start a block level element after the php tag.

Sometimes, you are generating plain text for inside a textarea.

Other times, you are not generating HTML strings at all.

  • SQL statement
  • email body
  • other non-HTML strings

You can make this slightly more elegant:

<?=$var.PHP_EOL?>

But in the end this is just a missing feature: If you're not in HTML/XML-context, just want to output simple, pure text you WANT to output the text "as is" and not have magically stripped the newlines away.

If this is causing a problem for you, you're most likely not writing good HTML. If you have PHP separated out from the HTML, then after the ?> close tag, just start with a block level HTML element.

Like this:

Hello <?php $php_code(); ?> <div>Something else here</div> or even <p>Something else here</p>

Which would output:

Hello

Something else here

If instead you're writing:

Hello <?php $php_code(); ?> Something else here

Then your problem is in how you're writing HTML, not PHP parsing.

Related