CoderZone.org
Pages: 1 « previous     next »
  Print  
Author Topic: Parsing PHP in a javascript file  (Read 4691 times) Bookmark and Share
Telonik
Newbie
*
Posts: 5



View Profile
« on: Dec 07, 2010, 08:40:48 am »

Here's a handy trick I found online a while back: how to parse and run PHP inside of an external javascript .JS file.

In your .htaccess file, add this bit:

Code:  
Highlight Mode: (Apache configuration)
  1. <FilesMatch "^.*?parsephp.*?$">
  2. SetHandler php5-script
  3. </FilesMatch>
 

This tells Apache to process any file that includes the string "parsephp" as a PHP file. (You may want to alter the RegEx to suit your needs.)

Next, in the JavaScript file itself, set the ContentType back to JavaScript:

Code:  
Highlight Mode: (PHP)
  1. <?php
  2.        // Set the content type back to javascript
  3.        header("Content-type: application/javascript");
  4. ?>
 

What this does is make sure that browsers reading the JS file will parse it as JavaScript. But placing <php ... ?> tags inside the JavaScript file will also run any embedded PHP code as well. This way you can do some tricky (and useful) combining of JS vars and PHP code or PHP vars and JS code.

This would also work in style sheets to provide dynamic CSS for skins or themes. Smiley

Logged
Tags:
Pages: 1
  Print  
 
Jump to: