<script type="text/javascript">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.
<?php
echo " alert('This is dynamically coded JavaScript!');";
?>
</script>
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:
<?phpThe 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.
$exampleVar = 5;
?>
p{
width: <?php echo $exampleVar; ?>in;
height: <?php echo $exampleVar * 2; ?>in;
}
In my CSS and JS files with PHP, I use this algorithm to either link (client-side) or include (server-side) the script:
<?phpNote 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.
if(isset($method)) $included = $method == 'include';
if($included) echo "<style type="\"text/css\"">\n";
?>
//insert code here
<?php
if($included) echo "</style>\n";
?>
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.)
<?phpSee Wikipedia: Internet media type.
header('Content-Type: text/xml');
?>
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.
No comments:
Post a Comment