Friday, September 14, 2007

HTML Isn't PHP's Only Application.

I recently completed an online certification (probably worthless in industry) in PHP; during that course, I accidentally found this article while searching for something else on the site. As a JavaScript programmer, I found this very intriguing. As I was experimenting with this new twist on the two languages, I found that this also works:
<script type="text/javascript">
<?php
    echo "    alert('This is dynamically coded JavaScript!');";
?>
</script>
It works because <?php and ?> aren't HTML code; they're signals to the PHP engine telling it to start and stop parsing PHP code, respectively.

Dynamic CSS is another application of PHP. If, for example, you have two (or more) CSS values which are related, you can figure both from one PHP variable:
<?php
    $exampleVar = 5;
?>
p{
    width: <?php echo $exampleVar; ?>in;
    height: <?php echo $exampleVar * 2; ?>in;
}
The above code makes all P elements 10 inches high and 5 inches wide. To apply another set of dimensions of the same proportion (height = width * 2), just change $exampleVar. Of course, the variable could be dynamic as well, but I didn't feel like putting that much into an example.

In my CSS and JS files with PHP, I use this algorithm to either link (client-side) or include (server-side) the script:
<?php
    if(isset($method)) $included = $method == 'include';
    if($included) echo "<style type="\"text/css\"">\n";
?>

//insert code here

<?php
    if($included) echo "</style>\n";
?>
Note that, to include the file, you must specify "$method = 'include'" first. You could use "$included = true" instead, but the above way leaves the script open to other operations for other values of $method.

Any other client-side code could probably benefit from PHP, too, although I haven't tried it. I wonder what enhancements, if any, would be possible in XML (and its many branches), for instance. If the browser doesn't know what language to interpret the file in (i.e., due to <a href="http://www.blogger.com/script.xml.php" mce_href="script.xml.php">an ambiguous link</a>), some problems might arise, although I think the browser should recognize the markup in this case.

NOTE (early 2008): I recently noticed that PHP has a solution to this problem. Send a header like this one (for the above example) and the browser will interpret the file correctly. (Apache HTTPD also has a solution in its [httpd.conf / apache.conf] and directory-specific .htaccess files.)
<?php
    header('Content-Type: text/xml');
?>
See Wikipedia: Internet media type.

As you surely noticed, the above filename ends in .xml.php. I think it's a good idea to use the conventional file extension (i.e., .js, .css) before the .php, if only for your own recollection when you're trying to find that pesky file among all the other .php extensions. Ideally, this kind of compound extension would be recognized by IDEs, etc., but I won't hold my breath.