使用 "file_put_contents" 创建和编辑文件 javascript?

Create and edit file javascript with "file_put_contents"?

我想用 php 创建一个 file.js,但我认为我的代码中有很多错误:

我有多维数组:

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

即:

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

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

设置js文件的内容类型

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

有两个问题:

1) 启动时 file.php 要求我下载相同的文件,但在 javascript

2) 在 "outvulcani" 中它创建了文件 report.js 但它是空的

我希望文件 "report.js" 中有数组 $report 但是 用 javascript 代码编写:

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

你能帮帮我吗?

非常感谢! 对不起我的英语

PHP 具有将数组转换为 JSON 的函数。您可以将此代码用于 "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);

"Download"的原因是header,请删除。