简体   繁体   中英

how can i generate Javascript and with PHP and put it into a .js file

I want to generate javascript dinamically with php, but i want the code to appear in a different file, and call it from my index file in order to have a better structured code.

Do you know a good way to do so?

I don't think it's good idea. It's better to put static JS code into file and pass only needed variables from PHP to HTML (not to JS file).

But if you want to do it, you can use, eg. file_put_contents() to write to file. Or any other function that can do that (there are many ways).

Also you can consider using .htaccess to change, eg. scripts.php to script.js and generate JS code from it without saving each time to file.

You can name a file anything you want as long as the file name ends with .php (or whatever extension is run by PHP).

In the past I have used a file name like script.js.php so that I know it's JavaScript built by PHP.

At the beginning of the file make sure you change the mime type. This has to be at the very beginning of the file with no white space before it.

<?php header("Content-type: text/javascript"); ?>

In your index file you would reference it like common JavaScript.

<script src="script.js.php"></script>

After your header you would have code like this:

var data = <?php echo json_encode($data); ?>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM