Generate Javascript Files with PHP

Posted August 22nd @ 9:18 am  |  Filed in: PHP    

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!

No Comments Yet

You can be the first to comment!

Leave a comment

OpenID Login

Standard Login

Options:

Size

Colors