Easier way to dynamically create Javascript using PHP
I'm currently using PHP to dynamically create a javascript which will be echoed
on the page.
Sample Code:
$JS .= '<script>';
if($condition == true) {
$JS .= 'alert("Yo its true omg!");
}
$JS .= "</script>";
As you can see, this will eventually get messy with ll the '
quotes and escaping of single quotes within the double quotes...
I开发者_开发百科s there a better way to do this?
You want the heredoc syntax!
if($condition)
$statement = <<<JS
alert("Wohoo!");
JS;
else $statement = "";
$javascript = <<<JS
<script>
$statement
</script>
JS;
To handle conditional statements inside heredoc strings, simply do the condition logic beforehand and insert empty or filled strings inside the heredoc string. You can insert variables into heredoc strings the same way you do normal strings.
If you think heredoc strings are a hassle to define, I agree with you. Unfortunately, as far as I know, it's the only way to escape the even greater quote escaping hassle (No pun intended).
You would be better to create the dynamic javascript file still as a separate file with the PHP extension then just before outputting the javascript set the header content type to text/javascript
$js = <<<JS
// Your JS here
JS;
header("Content-type: text/javascript");
echo $js;
exit();
Create a PHP file, but use a content header to make it 'look' like a JS file to the Browser. Because the file extension is .php Apache (or whatever other web server you're using) will still parse it, but the browser will see it as a JS file and run the contents properly. I use this frequently for CSS files because it allows me to declare variables and take advantage of loops and other more powerful control concepts lacking from CSS.
If the static javscript code amount is more than your dinamically created javascript code amount, you can simply write javascript code as usual and then inject php where needed.
Example of a hypothetical index.php:
<?php
$message = "Yo its true omg!";
?>
<html><head>
<script>
alert("<?php echo $message; ?>");
</script>
</head><body>
...
</body></html>
echo <<<EOF
<script>
alert("Yo it's true omg!");
</script>
EOF;
精彩评论