This article mainly introduces two examples of PHP Dynamic javascript file generation. For more information, see
I. dynamic PHP generation
Step 1: directly write JS code in the PHP file, and declare in the header that this is a JavaScript file
The code is as follows:
Step 2: use PHP to output escape JavaScript code
The code is as follows: function jsformat ($ str)
{
$ Str = trim ($ str );
$ Str = str_replace ('\ s \ S',' \ S', $ str );
$ Str = str_replace (chr (10), '', $ str );
$ Str = str_replace (chr (13), '', $ str );
$ Str = str_replace ('','', $ str );
$ Str = str_replace ('\\',' \\\\ ', $ str );
$ Str = str_replace ('"', '\"', $ str );
$ Str = str_replace ('\\\'',' \\\\\'', $ str );
$ Str = str_replace ("'", "\'", $ str );
Return $ str;
}
Directly call jsformat ($ str)
Last step: rewrite the url. for example, if the PHP address is xxx/123.php, rewrite it to xxx/123.js.
Taking PHPCMS as an example
The code is as follows:
{Pc: content action = "position" posid = "1" order = "id DESC" num = "7" $ catid = 11}
Function jsformat ($ str ){
$ Str = trim ($ str );
$ Str = str_replace ('\ s \ S',' \ S', $ str );
$ Str = str_replace (chr (10), '', $ str );
$ Str = str_replace (chr (13), '', $ str );
$ Str = str_replace ('','', $ str );
$ Str = str_replace ('\\',' \\\\ ', $ str );
$ Str = str_replace ('"', '\"', $ str );
$ Str = str_replace ('\\\'',' \\\\\'', $ str );
$ Str = str_replace ("'", "\'", $ str );
Return $ str;
}
?>
{Loop $ data $ v}
Document. writeln (" ");
{/Loop}
{/Pc}
Every loop uses document. writeln () to write the code after transfer.
II. PHP include JS files
Use html to write javascript to introduce a php link. This php actually generates a js file:
The code is as follows:
If (20 = $ ad_type_id) {// couplet
Ob_start ();
Include TMPL_PATH. 'code/duilian. js ';
Header ("content-type: application/x-javascript ");
$ Code = ob_get_clean ();
Echo $ code;
}
Include the js file in php and the var swf variable in js. var swf = ''. ob cache is used here. Note that the header (" content-type: application/x-javascript) to let the browser know that this is a javascript script file.
Reference on the page as follows:
The code is as follows: