0

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?

4
  • If it is generated code, why do you want to put it in a separate file ? Commented Oct 18, 2013 at 16:19
  • 2
    In general, the less dynamically generated JS code you have, the better. Ideally, your JS code should be entirely static, and only the initial data for it would be dynamic. Commented Oct 18, 2013 at 16:20
  • "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." A really, really bad idea, for many, many different reasons. Complexity. Performance/overhead. Security. Unnecessary processing. Unnecessary I/O. Additional risk points/failure points. Etc. etc. Don't do it :) Commented Oct 18, 2013 at 16:44
  • For instance, i need to generate graphs dinamically, if i use static js i will have a limited number of graphs Commented Oct 19, 2013 at 20:18

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.