简体   繁体   中英

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

213123123
213123124
123412321

and i need to retrieve random value from above text file ..for example 213123124 from above text file

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:

echo intval($file[$rand]);

Edit: Seeing as intval() returns the max_int for numbers that exceed int specs, just use 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.

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. This allows for easy handling of information.

And remember to save many smaller files , rather than a large one...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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