简体   繁体   English

如何将数组存储在文件中,以便以后使用PHP作为数组访问?

[英]How do I store an array in a file to access as an array later with PHP?

I just want to quickly store an array which I get from a remote API, so that i can mess around with it on a local host. 我只想快速存储一个从远程API获得的数组,以便可以在本地主机上处理它。

So: 所以:

  1. I currently have an array. 我目前有一个数组。
  2. I want to people to use the array without having to get it from the API. 我希望人们不必从API获取数组就可以使用它。

There are no needs for efficiency etc here, this isnt for an actual site just for getting some sanitizing/formatting methods made etc 这里不需要效率等,对于实际站点而言,这并不是为了获得一些消毒/格式化方法等。

Is there a function like store_array() or restore_arrray() ?! 有没有像store_array()restore_arrray()这样的函数?

The best way to do this is JSON serializing. 最好的方法是JSON序列化。 It is human readable and you'll get better performance (file is smaller and faster to load/save). 它是人类可读的,您将获得更好的性能(文件更小,加载/保存更快)。 The code is very easy. 代码很简单。 Just two functions 只有两个功能

Example code: 示例代码:

$arr1 = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
file_put_contents("array.json",json_encode($arr1));
# array.json => {"a":1,"b":2,"c":3,"d":4,"e":5}
$arr2 = json_decode(file_get_contents('array.json'), true);
$arr1 === $arr2 # => true

You can write your own store_array and restore_array functions easily with this example. 通过此示例,您可以轻松编写自己的store_array和restore_array函数。

For speed comparison see benchmark originally from Preferred method to store PHP arrays (json_encode vs serialize) . 为了进行速度比较,请参阅最初来自Preferred方法的 基准测试 以存储PHP数组(json_encode与serialize)

If you don't need the dump file to be human-readable, you can just serialize() the array. 如果您不需要转储文件是人类可读的,则只需对数组进行serialize()

storing: 存储:

file_put_contents('yourfile.bin', serialize($array));

retrieving: 检索:

$array = unserialize(file_get_contents('yourfile.bin'));

Use serialize and unserialize 使用序列化和反序列化

// storing
$file = '/tmp/out.data';
file_put_contents($file, serialize($mydata)); // $mydata is the response from your remote API

// retreiving
$var = unserialize(file_get_contents($file));

Or another, hacky way: 或另一种怪异的方式:

var_export() does exactly what you want, it will take any kind of variable, and store it in a representation that the PHP parser can read back. var_export()可以完全满足您的要求,它将使用任何类型的变量,并将其存储在PHP解析器可以读取的表示形式中。 You can combine it with file_put_contents to store it on disk, and use file_get_contents and eval to read it back. 您可以将其与file_put_contents组合以将其存储在磁盘上,并使用file_get_contentseval来将其读回。

// storing
$file = '/tmp/out.php';
file_put_contents($file, var_export($var, true));

// retrieving
eval('$myvar = ' . file_get_contents($file) . ';');

You can use serialize to make it into a string to write to file, and the accompanying unserialize to return it to an array structure. 您可以使用序列化将其转换为字符串以写入文件,并使用附带的反序列化将其返回到数组结构。

I'd suggest using a language independent structure though, such as JSON. 我建议尽管使用与语言无关的结构,例如JSON。 This will allow you to load the files using different languages than PHP, in case there's a chance of that later. 这将允许您使用不同于PHP的语言来加载文件,以防日后再有这种情况。 json_encode to store it and json_decode ($str, true) to return it. json_encode存储它,而json_decode ($str, true)返回它。

Another fast way not mentioned here: 这里没有提到的另一种快速方法:

That way add header with <?php start tag, name of variable \\$my_array = with escaped \\$ and footer ?> end tag. 这样,可以添加带有<?php开始标记的标头,带有转义的\\$和页脚?>结束标记的变量\\$my_array =名称。

Now can use include() like any other valid php script. 现在可以像其他任何有效的php脚本一样使用include()

// storing
$file = '/tmp/out.php';
file_put_contents($file, "<?php\n\$my_array = ".var_export($var, true).";\n?>");

// retrieving as included script
include($file);

//testing
print_r($my_array);

out.php will look like this out.php看起来像这样

<?php
  $my_array = array (
    'a'=>1,
    'b'=>2,
    'c'=>3,
    'd'=>4,
    'e'=>5
  );
?>

使用php的serialze:

file_put_contents("myFile",serialize($myArray));

Talking about php use, for performance sake, avoid encoding and decoding everything, just save array with: 谈论php的使用,出于性能考虑,避免对所有内容进行编码和解码,只需将数组保存为:

 file_put_contents('dic.php', "<?php \n".'$dic='.var_export($dic, true).';');

and call normally with 并正常拨打

include "dic.php";

I made a tiny library (~2 KB; <100 lines) that allows you to do just this: varDx 我做了一个很小的库( 〜2 KB; <100行),您可以做到这一点: varDx

It has functions to write, read, modify, check and delete data. 它具有写入,读取,修改,检查和删除数据的功能。 It implements serialization, and therefore supports all data types. 它实现序列化,因此支持所有数据类型。

Here's how you can use it: 使用方法如下:

<?php
require 'varDx.php';
$dx = new \varDx\cDX; //create an object
$dx->def('file.dat'); //define data file

$val1 = "this is a string";
$dx->write('data1', $val1); //writes key to file
echo $dx->read('data1'); //returns key value from file

In your specific case: 在您的特定情况下:

$array1 = array(
    "foo" => "bar",
    "bar" => "foo",
);

//writing the array to file
$dx->write('myarray', $array1);

//reading array from file
$array2 = $dx->read('myarray')

//modifying array in file after making changes
$dx->write('myarray', $array2);

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

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