There are times when you might want to fetch stuff from a database using PHP and then spit out a JavaScript file. For example, many image slideshows are controlled by javascript - but what if the image references are stored in MySQL? You can use PHP to fetch the info, and then include the javascript/php file in the <head> of your HTML page, something like this:
<script type="text/javascript" src="/includes/slideshow.js.php"></script>
The above file is being called by the browser as a JavaScript file - but because it has the ".php" extension, the server knows that it has some php work to do before it delivers the file to the browser.
However, there's one gotcha...
My JavaScript File Doesn't Have Line Breaks!
I admit I had to beat my head on the desk for awhile, until it dawned on me that this could be fixed by adding a simple header call to the top of the PHP file:
Header("content-type: application/x-javascript");
Now, all output will maintain the linebreaks that javascript so depends on. In the PHP code, just add the newline character where you need a line break, like so:
echo "\n";
Cheers!

By Matt October 27, 2011 - 3:31 pm
Thanks A.Coward – but the article is about outputting javascript with your own php script, not minifying. For example, inserting php variables into the js file before the js gets processed. If you know a better way please please post it.
By Anonymous Coward October 27, 2011 - 2:32 pm
With the guideline and tips today, on how to minify the javascript, linebreaks are rarely an issue. Look at the libraries – mostly defined in just one line. :-)
By Javascript Files with PHP | My Monkey Do October 5, 2011 - 8:18 pm
[...] http://www.givegoodweb.com/post/71/javascript-php [...]
By Aline January 6, 2011 - 5:29 am
Thanks for the tip!
I solve the linebreaks scaping the “\n”, like this:
\\n
It worked for me! =D
By Jotham March 14, 2010 - 4:29 pm
I had mine all up and running, except the .js.php extension. Thanks much.