4

I have a code like this which is created using php

<?php
$script="$(document).ready(function(){alert('hai');});";
?>

As far as I have referred in other websites, they have used fopen() and fwrite() to open a text file and write in it. I don't want txt file to be created.Can I create a script file say script.js that contains data in the $script variable using php?

3
  • just have the php script file print out the script code, and then in like your <script> tag make src point to your php script. Make sure to do a header('Content-Type: text/javascript'); before hand so browser will interpret it correctly. Commented Aug 30, 2013 at 16:43
  • It is not static.The js code created varies. so I have to create each js file whenever the php file is executed Commented Aug 30, 2013 at 16:44
  • which is why you point it at the php script, and do the processing that needs done in the script before printing out. Commented Aug 30, 2013 at 16:45

2 Answers 2

8

This will create file called script.js and contains your JS statements:

$script="$(document).ready(function(){alert('hai');});";
$fileName="script.js";
file_put_contents($fileName, $script);
Sign up to request clarification or add additional context in comments.

1 Comment

please rename the variable name $file to $filename
1

do you mean like..

file_put_contents()

https://www.php.net/manual/en/function.file-put-contents.php

<?php
$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>

Otherwise im not sure what you are asking.

3 Comments

It copies and append code from one file to another. But I have to create a fresh js file whenever the php file is executed
you can do that excatly with my script... u do need to modify it to what you need excatly, since i do not really understand what you need i cant do much else. But i think another also made a comment. maybe that is more what you need :-) Best of luck
Thanks for your solution. file_put_contents() creates a file directly.Instead of copying from another text file, we need to write our data and create it. I have marked the right answer above. That is what the solution I expected.

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.