使用"file_put_content "创建和编辑文件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)启动文件时,php要求我下载相同的文件,但在javascript

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

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

var reports = [
 [3,6]
 [4,8]
];
劳驾,你能帮我一下吗?

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

PHP有一个将数组转换为JSON的函数。你可以把这段代码用作"灵感"。

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

"下载"的原因是标题,请删除它