简体   繁体   English

在PHP脚本中包含文本文件中的数组

[英]Include array from text file in PHP script

I am making a script that outputs a nested array to a text file in PHP. 我正在制作一个脚本,该脚本将嵌套数组输出到PHP中的文本文件。 However I am struggling to get other scripts to use the array when I use include('array.txt'); 但是,当我使用include('array.txt');时,我正在努力让其他脚本使用数组include('array.txt');

I have tried several different methods like $var = include('array.txt'); 我尝试了几种不同的方法,例如$var = include('array.txt'); or just the include with the var defined inside the text file to no avail. 或仅包含文本文件内定义的var都没有用。

It is important to note that this file only ever wants to be generated once and the array should not change after that (hence the method of outputting to a text file) 重要的是要注意,此文件只想生成一次,并且此后数组不应更改(因此,输出到文本文件的方法)

Here is an example of what the array file looks like. 这是数组文件的示例。

array(array('2','30','37','43','104','152','166','193'),array('10','60','95','112','116','163','199','240','242'),array('12','44','80','91','128','138','140','231'),array('19','38','102','111','130','134','175','207','210','246'))

What is the correct way to do this? 正确的方法是什么?

Use serialization: 使用序列化:

file_put_contents ($filename, serialize ($array)); // write to file
$array = unserialize (file_get_contents ($filename)); // retrieve

Or JSON encoding: 或JSON编码:

file_put_contents ($filename, json_encode ($array)); // write to file
$array = json_decode (file_get_contents ($filename), true); // retrieve

Also, it might be a good idea to use gzip encoding to save disk space. 同样,使用gzip编码来节省磁盘空间可能是一个好主意。 (using gzencode() and gzdecode() ) (使用gzencode()gzdecode()

The easiest way would be to change the file extension to .php for the output file. 最简单的方法是将输出文件的文件扩展名更改为.php。 A .php is just a text file with the .php extension. .php只是扩展名为.php的文本文件。 Then you can use the include function to include the php file. 然后,您可以使用include函数包含php文件。

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

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