Home >Backend Development >PHP Tutorial >2 examples of dynamically generating javascript files with PHP_PHP Tutorial

2 examples of dynamically generating javascript files with PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:32:52973browse

1. PHP dynamic generation

Step one: Write JS code directly in the PHP file and declare in the header that this is a JavaScript file

Copy the code The code is as follows:

Step 2: Escape JavaScript with PHP output Code
Copy 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)
The last step: proceed URL rewriting, for example, the PHP address is xxx/123.php, as long as it is rewritten to xxx/123.js, the purpose has been achieved.

Take PHPCMS as an example

Copy the code The code is as follows:
< ?php header('Content-Type: application/x-javascript; charset=UTF-8');?>
{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}

Use document.writeln() to write the transferred code in each cycle.

2. PHP include JS file

Introduce a php link by writing javascript in html. The php is actually a file that generates js:

Copy the code 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 js files in php, variables such as var swf in js, var swf = '', use ob cache here, pay attention to add header ("content-type: application/x-javascript") to allow browsing The server knows that this is a javascript script file.

The page is quoted like this:

Copy the codeThe code is as follows:

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752917.htmlTechArticle1. The first step of PHP dynamic generation: write JS code directly in the PHP file and declare it in the header This is a JavaScript file. Copy the code as follows: ?php header('Content-Type: applica...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn