0

i would like to create a file.js with php but i think that in my code there are a lot of errors:

i have multidimensional array:

$report= array();   
$report= array(array(3,6),array(4,8));

that is:

Array
(
    [0] => Array
      (
        [0] => 3
        [1] => 6
      )

   [1] => Array
      (
        [0] => 4
        [1] => 8
      )
)

Set a content-type for js file

$header = "Content-type: text/javascript";
$dir = "outreport/";
$nomefile = "report.js";

//delete a file with same name if exists 
foreach (glob($dir."*".$nomefile) as $v){
  unlink($v);   
}

$percorso = $dir.$nomefile;
file_put_contents($percorso, $report);
header($header);
print($report);

There are two problems:

1) when launching the file.php asks me to download the same file but in javascript

2) in the "outvulcani" it creates the file report.js but is empty

I wish that in the file "report.js" there is the array $report but written in javascript code:

var reports = [
 [3,6]
 [4,8]
];

Kindly, you can help me out?

Thanks a lot! Sorry for my english

4
  • "when launching the file.php asks me to download the same file but in javascript" — What did you expect to be sent to the browser? Commented Aug 1, 2015 at 14:04
  • "in the "outvulcani" it creates the file report.js but is empty" — I can't reproduce that problem, but nowhere in your code is anything that would construct the JS you list in your desired output. Commented Aug 1, 2015 at 14:05
  • @Quentin and how i can construct JS list in desired output ? you can help me ? thanks a lot ! P.s. ask at your first question, why the browser ask me to download a file in js ? I thought that launching file.php merely creates "report.js" folder "outvulcani" Commented Aug 1, 2015 at 14:10
  • What do you think header and print do then? Commented Aug 1, 2015 at 14:13

1 Answer 1

1

PHP has an function to convert Arrays to JSON. You could use this code for "inspiration".

$report = array(array(3,6),array(4,8));
$javascriptContent = json_encode($report);

// Convert to string
$javascriptContent = "var reports = ". $javascriptContent . ";\n";
file_put_contents($percorso, $javascriptContent);

The reason for "Download" is the header, please remove it.

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

1 Comment

i used your code and removed the header and now doesn't ask me to download a file, and there is js file "report.js". Thanks !

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.