将数组保存到 PHP 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18342477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:22:27  来源:igfitidea点击:

Save array to PHP file

phparrays

提问by Mooseman

I have a PHP file to store an array:

我有一个 PHP 文件来存储一个数组:

<?php
  $arr = array (
    "A" => "one",
    "B" => "two",
    "C" => "three"
  );
?>

I am using requireto open the file, and each entry loads into a form. (foreachloop) I would like to save the $_POSTvariables back (overwriting) to the original file in the same format. I have no trouble making the form and sending back the variables. I just need a way to print the array back into the original file.

require用来打开文件,每个条目都加载到一个表单中。(foreach循环)我想以相同的格式$_POST变量保存回(覆盖)到原始文件。我可以轻松制作表格并发回变量。我只需要一种将数组打印回原始文件的方法。

Example result:

结果示例:

<?php
  $arr = array (
    "A" => "new value",
    "B" => "other new value",
    "C" => "third new value"
  );
?>

I have been unable to use print_r, as the format returned is incorrect. How can I do this successfully? Thank you.

我一直无法使用print_r,因为返回的格式不正确。我怎样才能成功地做到这一点?谢谢你。

回答by MosheK

The function you're looking for is var_export

您正在寻找的功能是 var_export

You would use it like this

你会像这样使用它

file_put_contents($filename, '<?php $arr = ' . var_export($arr, true) . ';');

DEMO

演示

回答by Jason Crittenden

You probably don't want to be re-writing your php code on the fly.

您可能不想即时重写您的 php 代码。

Two alternatives:

两种选择:

  1. Use a database

  2. Serializethe array, then (over)write to file. When reading the file, you will just want to unserializethe value.

  3. Use json_encodeand json_decodeas discussed in #2

  1. 使用数据库

  2. 序列化数组,然后(覆盖)写入文件。读取文件时,您只想反序列化该值。

  3. 使用#2 中讨论的json_encodejson_decode

回答by vinyll

There's actually several ways to achieve that.

实际上有几种方法可以实现这一目标。

  1. Open your file and write into it with file_put_contents() (http://php.net/manual/fr/function.file-put-contents.php)
  2. write to the file your array encoded to string with JSON.encode (http://www.php.net/manual/fr/function.json-encode.php)
  3. read your file with file_get_contents (file_get_contents)
  4. convert your string to an array with JSON.decode (http://www.php.net/manual/fr/function.json-decode.php)
  1. 打开您的文件并使用 file_put_contents() ( http://php.net/manual/fr/function.file-put-contents.php)写入文件
  2. 使用 JSON.encode ( http://www.php.net/manual/fr/function.json-encode.php)将您的数组编码为字符串写入文件
  3. 使用 file_get_contents (file_get_contents) 读取您的文件
  4. 使用 JSON.decode ( http://www.php.net/manual/fr/function.json-decode.php)将您的字符串转换为数组