javascriptphpmultidimensional-arrayphpjs

Create and edit file javascript with "file_put_contents"?


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


Solution

  • 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.