How to read an array from a text file?

I saved the array in a txt file using file_put_contents () in php, writefullu php array in text file, how at the same time how to read this text file in php?

<?php
$arr = array('name','rollno','address');
file_put_contents('array.txt', print_r($arr, true));
?>

The above PHP file writes a text file successfully. I want to read this text file in php?

+4
source share
4 answers

If you plan to reuse the same values ​​inside an array, you can use var_exportan array to create this file.

Basic example:

$arr = array('name','rollno','address');
file_put_contents('array.txt',  '<?php return ' . var_export($arr, true) . ';');

Then, when it comes time to use these values, just use include:

$my_arr = include 'array.txt';
echo $my_arr[0]; // name

Or just use a simple string JSON, then encode / decode:

$arr = array('name','rollno','address');
file_put_contents('array.txt',  json_encode($arr));

, :

$my_arr = json_decode(file_get_contents('array.txt'), true);
echo $my_arr[1]; // rollno
+5

$strarray = file_get_contents('array.txt');

.

0

FOPEN()

The first parameter fopen () contains the name of the file to be opened, and the second parameter indicates in what mode the file should be opened

Fread ()

The first parameter fread () contains the name of the file to read, and the second parameter indicates the maximum number of bytes read.

fclose ()

The fclose () function is used to close an open file.

$arr = array('name','rollno','address');
file_put_contents('array.txt', print_r($arr, true));

$myfile = fopen("array.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("array.txt"));
fclose($myfile);

Output:

Array ( [0] => name [1] => rollno [2] => address )
0
source

Use this:

$arr = file('array.txt', FILE_IGNORE_NEW_LINES);
print_r($arr);
0
source

Source: https://habr.com/ru/post/1649235/


All Articles