Ced
Ced

Reputation: 711

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?

Upvotes: 0

Views: 331

Answers (2)

iambriansreed
iambriansreed

Reputation: 22251

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); ?>;

Upvotes: 0

Elon Than
Elon Than

Reputation: 9765

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.

Upvotes: 1

Related Questions