简体   繁体   English

如何使用php将数据保存在文本文件中

[英]How to save data in text file using php

I need to save many variables in text file and later retrieve any one random data from the text document. 我需要在文本文件中保存许多变量,然后再从文本文档中检索任意一个随机数据。

For Example ...i need to add 31231231 to the below text file 例如...我需要将31231231添加到以下文本文件中

213123123
213123124
123412321

and i need to retrieve random value from above text file ..for example 213123124 from above text file 我需要从上面的文本文件中检索随机值。例如,从上面的文本文件中获取213123124

To write to the already existing file : 写入现有文件:

file_put_contents("file.txt","\n31231231",FILE_APPEND);

To get a random value from the file : 要从文件中获取随机值:

$file = file("file.txt")
$len = count($file);
$rand  = rand ( 0, $len-1 );
echo $file[$rand];

Edit: While retrieving the PHP_EOL is included so do this: 编辑:包括在检索PHP_EOL时,请这样做:

echo intval($file[$rand]);

Edit: Seeing as intval() returns the max_int for numbers that exceed int specs, just use trim(); 编辑:看到intval()返回max_int超过int规格的数字,只需使用trim();

echo trim($file[$rand])

To write in to a file you can use : 要写入文件,您可以使用:

file_put_contents("test.txt","31231231".PHP_EOL ,FILE_APPEND);

Here PHP_EOL outputs \\r\\n or \\n depending on the OS. 在此,PHP_EOL根据操作系统输出\\ r \\ n或\\ n。

To select a random value from the text file you can use: 要从文本文件中选择一个随机值,可以使用:

$file = file("test.txt")
$file_length = count($file);
$random_value  = rand ( 0, $file_length-1 );
echo $file[$random_value];

New Edit: 新编辑:

If you want to avoid new line at the retrieved output you can do : 如果要避免在检索到的输出处换行,可以执行以下操作:

echo intval($file[$random_value]);

Hope this helps 希望这可以帮助

To save and access variables and information when stored as text, in db or flat files, create array of the data first, then use serialize() on the data before saving, and unserialize() after fetching again. 要保存和访问以文本形式存储在db或平面文件中的变量和信息,请先创建数据数组,然后在保存之前对数据使用serialize(),并在再次获取后使用unserialize()。 This allows for easy handling of information. 这样可以轻松处理信息。

And remember to save many smaller files , rather than a large one... 并记住要保存许多较小的文件,而不要保存较大的文件...

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

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