简体   繁体   English

如何将更新后的数组写入PHP文件

[英]How can I write an updated array into a PHP file

I'm building something in PHP which reads from a PHP file, which looks like this: 我正在用PHP构建一些东西,该东西从一个PHP文件读取,如下所示:

<?php

return [
'name' => 'John Smith'
];

In my code, I'm getting the contents of the file and I'm reading it. 在我的代码中,我正在获取文件的内容并正在读取它。 But here's my problem. 但这是我的问题。 When I want to add an item to that array, I can but I'm not sure how to save it back into that array file. 当我想向该阵列中添加项目时,可以但我不确定如何将其保存回该阵列文件中。

I've tried these ways of doing it ($array being the updated array) 我已经尝试过这些方法($ array是更新后的数组)

file_put_contents('file.php', var_export($array, true));
file_put_contents('file.php', print_r($array, true));

使用var_export()将数组放回文件中,如下所示:

file_put_contents('file.php', '<?php return ' . var_export($array, true) . ';');

As I see @misorude already suggested you need parameter 2 of var_export to be set to true as below 如我所见,@ misorude已经建议您需要将var_export参数2设置为true,如下所示

$ids = ['t1'=>10, 't2'=> 12, 't3' => 5];

$str = '<?php ' . PHP_EOL
        . 'return '
        . var_export($ids, 1) . ';' ;

echo $str;

RESULT: 结果:

<?php 
return array (
  't1' => 10,
  't2' => 12,
  't3' => 5,
);

So just write $str to a file and you are done 所以只需将$ str写入文件即可

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM