Как записать PHP массив в файл и считать его из файла
@E_p, спасибо за дополнение. Выбор между serialize() и json_encode() зависит от многих факторов, но serialize() более роднее для PHP.
21 апр 2017 в 21:07
Если массив «большой», например, занимает в памяти 20M, и у PHP в конфиге стоит ограничение на объем используемой памяти, например, 32M, то промежуточная переменная $data может вызвать ошибку 500. Было бы интересно решение без $data.
– user239133
21 апр 2017 в 22:08
@Руслан, да, но перед этим нужно все равно сериализовать данные. От ситуации с файлом особо не отличается. Postgres или SQLite, по крайней мере, на уровне C API предоставляют что-то типа дескрипторов файлов для BLOB-полей.
Как записать массив в файл php
В PHP есть встроенная функция serialize , которая позволяет преобразовывать переменные в пригодный для хранения формат. Минус в том, что формат, в котором будет значение — чисто PHPшное. Т.е. это не универсальный способ хранения. Бывает, что нужно эти данные потом куда-то передать. Тогда можно воспользоваться преобразованием массива в json с помощью функции json_encode . Для записи в файл есть встроенная функция file_put_contents
$data = [ 'user' => 'name', 'email' => 'feycot@gmail.com' ]; file_put_contents(__DIR__ . '/data.txt', serialize($data)); // a:2: file_put_contents(__DIR__ . '/data.json', json_encode($data)); //
file
Замечание:
Можно также использовать функцию file_get_contents() для получения файла в виде строки.
Список параметров
Подсказка
Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция fopen wrappers. Смотрите более подробную информацию об определении имени файла в описании функции fopen() . Смотрите также список поддерживаемых обёрток URL, их возможности, замечания по использованию и список предопределённых констант в разделе Поддерживаемые протоколы и обёртки.
В качестве необязательного параметра flags может можно указать одну или более следующих констант: FILE_USE_INCLUDE_PATH Ищет файл в include_path. FILE_IGNORE_NEW_LINES Пропускать новую строку в конце каждого элемента массива FILE_SKIP_EMPTY_LINES Пропускать пустые строки FILE_NO_DEFAULT_CONTEXT Не использовать контекст по умолчанию
Возвращаемые значения
Возвращает файл в виде массива. Каждый элемент массива соответствует строке файла, с символами новой строки включительно. В случае ошибки file() возвращает false .
Замечание:
Каждая строка в полученном массиве будет завершаться символами конца строки, если только не используется FILE_IGNORE_NEW_LINES ).
Замечание: Если у вас возникают проблемы с распознаванием PHP концов строк при чтении или создании файлов на Macintosh-совместимом компьютере, включение опции auto_detect_line_endings может помочь решить проблему.
Ошибки
Вызывает ошибку уровня E_WARNING , если файл не существует.
Примеры
Пример #1 Пример использования file()
// Получает содержимое файла в виде массива. В данном примере мы используем
// обращение по протоколу HTTP для получения HTML-кода с удалённого сервера.
$lines = file ( ‘http://www.example.com/’ );
?php
// Осуществим проход массива и выведем содержимое в виде HTML-кода вместе с номерами строк.
foreach ( $lines as $line_num => $line ) echo «Строка # : » . htmlspecialchars ( $line ) . «
\n» ;
>
// Используем необязательный параметр flags
$trimmed = file ( ‘somefile.txt’ , FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
?>
Примечания
Внимание
При использовании SSL, Microsoft IIS нарушает протокол, закрывая соединение без отправки индикатора close_notify . PHP сообщит об этом как «SSL: Fatal Protocol Error» в тот момент, когда вы достигнете конца данных. Чтобы обойти это, вы должны установить error_reporting на уровень, исключающий E_WARNING. PHP умеет определять, что на стороне сервера находится проблемный IIS при открытии потока с помощью обёртки https:// и не выводит предупреждение. Если вы используете fsockopen() для создания ssl:// сокета, вы сами отвечаете за определение и подавление этого предупреждения.
Смотрите также
- file_get_contents() — Читает содержимое файла в строку
- readfile() — Выводит файл
- fopen() — Открывает файл или URL
- fsockopen() — Открывает соединение с интернет-сокетом или доменным сокетом Unix
- popen() — Открывает файловый указатель процесса
- include — include
- stream_context_create() — Создаёт контекст потока
User Contributed Notes 15 notes
9 years ago
If the file you are reading is in CSV format do not use file(), use fgetcsv(). file() will split the file by each newline that it finds, even newlines that appear within a field (i.e. within quotations).
2 years ago
Be aware that using file() to count lines can cause OOM on the server as it’ll allocate all lines into an array.
If you’re dealing with files that can have thousands of lines, SplFileObject might be a better idea and with little changes you can get the same result.
10 years ago
To write all the lines of the file in other words to read the file line by line you can write the code like this:
$names = file ( ‘name.txt’ );
// To check the number of lines
echo count ( $names ). ‘
‘ ;
foreach( $names as $name )
echo $name . ‘
‘ ;
>
?>
this example is so basic to understand how it’s working. I hope it will help many beginners.
14 years ago
this may be obvious, but it took me a while to figure out what I was doing wrong. So I wanted to share. I have a file on my «c:\» drive. How do I file() it?
Don’t forget the backslash is special and you have to «escape» the backslash i.e. «\\»:
$lines = file ( «C:\\Documents and Settings\\myfile.txt» );
foreach( $lines as $line )
echo( $line );
>
hope this helps.
12 years ago
read from CSV data (file) into an array with named keys
. with or without 1st row = header (keys)
(see 4th parameter of function call as true / false)
function csv_in_array ( $url , $delm = «;» , $encl = «\»» , $head = false )
$csvxrow = file ( $url ); // —- csv rows to array —-
$csvxrow [ 0 ] = chop ( $csvxrow [ 0 ]);
$csvxrow [ 0 ] = str_replace ( $encl , » , $csvxrow [ 0 ]);
$keydata = explode ( $delm , $csvxrow [ 0 ]);
$keynumb = count ( $keydata );
if ( $head === true ) <
$anzdata = count ( $csvxrow );
$z = 0 ;
for( $x = 1 ; $x < $anzdata ; $x ++) <
$csvxrow [ $x ] = chop ( $csvxrow [ $x ]);
$csvxrow [ $x ] = str_replace ( $encl , » , $csvxrow [ $x ]);
$csv_data [ $x ] = explode ( $delm , $csvxrow [ $x ]);
$i = 0 ;
foreach( $keydata as $key ) <
$out [ $z ][ $key ] = $csv_data [ $x ][ $i ];
$i ++;
>
$z ++;
>
>
else <
$i = 0 ;
foreach( $csvxrow as $item ) <
$item = chop ( $item );
$item = str_replace ( $encl , » , $item );
$csv_data = explode ( $delm , $item );
for ( $y = 0 ; $y < $keynumb ; $y ++) <
$out [ $i ][ $y ] = $csv_data [ $y ];
>
$i ++;
>
>
?>
fuction call with 4 parameters:
(1) = the file with CSV data (url / string)
(2) = colum delimiter (e.g: ; or | or , . )
(3) = values enclosed by (e.g: ‘ or » or ^ or . )
(4) = with or without 1st row = head (true/false)
// —— view ——
echo «
\r\n" ;
print_r ( $csvdata );
echo "
\r\n» ;
// ——————
?>
PS: also see: http://php.net/manual/de/function.fgetcsv.php to read CSV data into an array
. and other file-handling methods
5 years ago
My experience is that the function file does uses the cached content if the file has changed.
4 years ago
As of PHP 5.6 the file(), file_get_contents(), and fopen() functions will return false if you are referencing a source URL that doesn’t have a valid SSL certificate. Presumably, you will run into this a lot in your development environments this will drive you crazy.
You will need to create a stream context and provide it as an argument to the various file operations to tell it to ignore invalid SSL credentials.
$args = array(«ssl»=>array(«verify_peer»=>false,»verify_peer_name»=>false),»http»=>array(‘timeout’ => 60, ‘user_agent’ => ‘Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/3.0.0.1’));
$context = stream_context_create($args);
$httpfile = file($url, false, $context);
16 years ago
This note applies to PHP 5.1.6 under Windows (although may apply to other versions).
It appears that the ‘FILE_IGNORE_NEW_LINES’ flag doesn’t remove newlines properly when reading Windows-style text files, i.e. files whose lines end in ‘\r\n’.
Solution: Always use ‘rtrim()’ in preference to ‘FILE_IGNORE_NEW_LINES’.
20 years ago
Note: Now that file() is binary safe it is ‘much’ slower than it used to be. If you are planning to read large files it may be worth your while using fgets() instead of file() For example:
$fd = fopen ( «log_file.txt» , «r» );
while (! feof ( $fd ))
<
$buffer = fgets ( $fd , 4096 );
$lines [] = $buffer ;
>
fclose ( $fd );
?>
The resulting array is $lines.
I did a test on a 200,000 line file. It took seconds with fgets() compared to minutes with file().
9 years ago
(«file()’s problem with UTF-16» is wrong. This is updated.
The former may miss the last line of the string.)
file() seems to have a problem in handling
UTF-16 with or without BOM.
file() is likely to think «\n»=LF (0A) as a line-ending.
So, not only «000A» but also «010A, 020A. FE0A, FF0A. «
are regarded as line-endings.
Moreover, file() causes a serious problem in UTF-16LE.
file() loses first «0A» (the first half of «0A00»)!
And the next line begins with «00» (the rest of «0A00»).
So lines after the first «0A» are totally different.
To avoid this phenomena,
eg. in case (php_script : UTF-8 , file : UTF-16 with line-ending «\r\n»),
mb_regex_encoding ( ‘UTF-16’ ); // to help mb_ereg_..() work properly
$str = file_get_contents ( $file_path );
$to_encoding = ‘UTF-16’ ; // encoding of string
$from_encoding = ‘UTF-8’ ; // encoding of PHP_script
$pattern1 = mb_convert_encoding ( ‘[^\r]*\r\n’ , $to_encoding , $from_encoding );
mb_ereg_search_init ( $str , $pattern1 );
while ( $res = mb_ereg_search_regs ()) $file [] = $res [ 0 ];
>
$pattern2 = mb_convert_encoding ( ‘\A.*\r\n(.*)\z’ , $to_encoding , $from_encoding );
mb_ereg ( $pattern2 , $str , $match );
$file [] = $match [ 1 ];
?>
instead of
$file = file($file_path);
If line-ending is «\n»,
$pattern1 = mb_convert_encoding(‘[^\n]*\n’, $to_encoding, $from_encoding);
15 years ago
A user suggested using rtrim always, due to the line ending conflict with files that have an EOL that differs from the server EOL.
Using rtrim with it’s default character replacement is a bad solution though, as it removes all whitespace in addition to the ‘\r’ and ‘\n’ characters.
A good solution using rtrim follows:
$line = rtrim ( $line , «\r\n» ) . PHP_EOL ;
?>
This removes only EOL characters, and replaces with the server’s EOL character, thus making preg_* work fine when matching the EOL ($)
15 years ago
If you’re getting «failed to open stream: Permission denied» when trying to use either file() or fopen() to access files on another server. Check your host doesn’t have any firewall restrictions in-place which prevent outbound connections. This is the case with my host Aplus.net
6 years ago
Using if ( file(name.txt) ) might not be enough for testing if the file was successfully opened for reading because the file could be empty in which case the array returned is empty, so test instead with !==. e.g.:
$file_array = file(‘test.txt’); // an empty file
echo »;
if ( $file_array ) # code.
echo «success\n»;
> else # code.
echo «failure\n»; // executed
>
if ( $file_array !== false ) # code.
echo «success\n»; // executed
> else # code.
echo «failure\n»;
>
echo ‘‘;
9 years ago
Here’s my CSV converter
supports Header and trims all fields
Note: Headers must be not empty!
function csv2array ( $file , $delim = ‘;’ , $encl = ‘»‘ , $header = false )
# File does not exist
if(! file_exists ( $file ))
return false ;
# Read lines of file to array
$file_lines = file ( $file , FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
# Empty file
if( $file_lines === array())
return NULL ;
# Read headers if you want to
if( $header === true ) $line_header = array_shift ( $file_lines );
$array_header = array_map ( ‘trim’ , str_getcsv ( $line_header , $delim , $encl ));
>
# Now line per line (strings)
foreach ( $file_lines as $line ) # Skip empty lines
if( trim ( $line ) === » )
continue;
# Convert line to array
$array_fields = array_map ( ‘trim’ , str_getcsv ( $line , $delim , $encl ));
# If header present, combine header and fields as key => value
if( $header === true )
$out [] = array_combine ( $array_header , $array_fields );
else
$out [] = $array_fields ;
>
16 years ago
Using file() for reading large text files > 10 Mb gives problems, therefore you should use this instead. It is much slower but it works fine. $lines will return an array with all the lines.
$handle = @ fopen ( ‘yourfile. ‘ , «r» );
if ( $handle ) <
while (! feof ( $handle )) <
$lines [] = fgets ( $handle , 4096 );
>
fclose ( $handle );
>
?>
- Copyright © 2001-2023 The PHP Group
- My PHP.net
- Contact
- Other PHP.net sites
- Privacy policy
array_fill
Заполняет массив count элементами со значением value , начиная с ключа start_index .
Список параметров
Первый индекс возвращаемого массива.
Если start_index отрицательный, первым индексом возвращаемого массива будет start_index , а последующие индексы будут начинаться с нуля до PHP 8.0.0; начиная с PHP 8.0.0, отрицательные ключи увеличиваются нормально (смотрите пример).
Количество добавляемых элементов. Должно быть больше или равно нулю и меньше или равно 2147483647 .
Значение для заполнения.
Возвращаемые значения
Возвращает заполненный массив.
Ошибки
Выбрасывает исключение ValueError в случае, если параметр count выходит за пределы диапазона.
Список изменений
| Версия | Описание |
|---|---|
| 8.0.0 | Функция array_fill() теперь выбрасывает исключение ValueError , если параметр count выходит за пределы диапазона; ранее выдавалась ошибка уровня E_WARNING , а функция возвращала значение false . |
Примеры
Пример #1 Пример использования array_fill()
$a = array_fill ( 5 , 6 , ‘banana’ );
print_r ( $a );
?>?php
Результат выполнения данного примера:
Array ( [5] => banana [6] => banana [7] => banana [8] => banana [9] => banana [10] => banana )
Пример #2 Пример использования array_fill() с отрицательным начальным индексом
$a = array_fill (- 2 , 4 , ‘pear’ );
print_r ( $a );
?>?php
Результат выполнения данного примера в PHP 7:
Array ( [-2] => pear [0] => pear [1] => pear [2] => pear )
Результат выполнения данного примера в PHP 8:
Array ( [-2] => pear [-1] => pear [0] => pear [1] => pear )
Обратите внимание, что индекс -1 отсутствует до PHP 8.0.0.
Примечания
Смотрите также подробное описание отрицательных ключей в разделе Массивы.
Смотрите также
- array_fill_keys() — Создаёт массив и заполняет его значениями с определёнными ключами
- str_repeat() — Возвращает повторяющуюся строку
- range() — Создаёт массив, содержащий диапазон элементов
User Contributed Notes 7 notes
19 years ago
This is what I recently did to quickly create a two dimensional array (10×10), initialized to 0:
$a = array_fill ( 0 , 10 , array_fill ( 0 , 10 , 0 ));
?>
This should work for as many dimensions as you want, each time passing to array_fill() (as the 3rd argument) another array_fill() function.
9 years ago
If you need negative indices:
$b = array_fill (- 2 , 4 , ‘pear’ ); //this is not what we want
$c = array_fill_keys ( range (- 2 , 1 ), ‘pear’ ); //these are negative indices
print_r ( $b );
print_r ( $c );
?>
Here is result of the code above:
Array
(
[-2] => pear
[0] => pear
[1] => pear
[2] => pear
)
Array
(
[-2] => pear
[-1] => pear
[0] => pear
[1] => pear
)
10 years ago
Using objects with array_fill may cause unexpected results. Consider the following:
//fill an array with objects
$array = array_fill ( 0 , 2 , new Foo ());
//now we change the attribute of the object stored in index 0
//this actually changes the attribute for EACH object in the ENTIRE array
$array [ 0 ]-> bar = «apple» ;
var_dump ( $array );
/*
array(2) [0]=>
object(Foo)#1 (1) [«bar»]=>
string(5) «apple»
>
[1]=>
object(Foo)#1 (1) [«bar»]=>
string(5) «apple»
>
>
*/
?>
Objects are filled in the array BY REFERENCE. They are not copied for each element in the array.
2 years ago
As of PHP 8.0 the example code
$b = array_fill (- 2 , 4 , ‘pear’ );
print_r ( $b );
?>
now returns
11 years ago
I made this function named «array_getMax» that returns te maximum value and index, from array:
//using array_search_all by helenadeus at gmail dot com
foreach ( $haystack as $k => $v )
if( $haystack [ $k ]== $needle )
$array [] = $k ;
>
>
return ( $array );
function array_getMax ( $array )
$conteo = array_count_values ( $array );
//$antValue=null;
$maxValue = null ;
$keyValue = null ;
foreach( $array as $key => $value ) <
if( $maxValue == null ) <
$maxValue = $value ;
$keyValue = $key ;
break;
>
>
$resultSearch = array_search_all ( $maxValue , $array );
return array_fill_keys ( $resultSearch , $maxValue );
//example
$arreglo =array( ‘e1’ => 99 , ‘e2′ => ’99’ , ‘e3’ => 1 , ‘e4’ => 1 , ‘e5’ => 98 );
var_dump ( array_getMax ( $arreglo ));
5 years ago
Fill missing keys in a (numerically-indexed) array with a default value
function fill_missing_keys ( $array , $default = null , $atleast = 0 )
return $array + array_fill ( 0 , max ( $atleast , max ( array_keys ( $array ))), $default );
>
21 years ago
array_fill() cannot be used to setup only missing keys in an array. This may be necessary for example before using implode() on a sparse filled array.
The solution is to use this function:
function array_setkeys (& $array , $fill = NULL ) <
$indexmax = — 1 ;
for ( end ( $array ); $key = key ( $array ); prev ( $array )) <
if ( $key > $indexmax )
$indexmax = $key ;
>
for ( $i = 0 ; $i if (!isset( $array [ $i ]))
$array [ $i ] = $fill ;
>
ksort ( $array );
>
?>
This is usefull in some situations where you don’t know which key index was filled and you want to preserve the association between a positioned field in an imploded array and the key index when exploding it.
- Функции для работы с массивами
- array_change_key_case
- array_chunk
- array_column
- array_combine
- array_count_values
- array_diff_assoc
- array_diff_key
- array_diff_uassoc
- array_diff_ukey
- array_diff
- array_fill_keys
- array_fill
- array_filter
- array_flip
- array_intersect_assoc
- array_intersect_key
- array_intersect_uassoc
- array_intersect_ukey
- array_intersect
- array_is_list
- array_key_exists
- array_key_first
- array_key_last
- array_keys
- array_map
- array_merge_recursive
- array_merge
- array_multisort
- array_pad
- array_pop
- array_product
- array_push
- array_rand
- array_reduce
- array_replace_recursive
- array_replace
- array_reverse
- array_search
- array_shift
- array_slice
- array_splice
- array_sum
- array_udiff_assoc
- array_udiff_uassoc
- array_udiff
- array_uintersect_assoc
- array_uintersect_uassoc
- array_uintersect
- array_unique
- array_unshift
- array_values
- array_walk_recursive
- array_walk
- array
- arsort
- asort
- compact
- count
- current
- end
- extract
- in_array
- key_exists
- key
- krsort
- ksort
- list
- natcasesort
- natsort
- next
- pos
- prev
- range
- reset
- rsort
- shuffle
- sizeof
- sort
- uasort
- uksort
- usort
- each
- Copyright © 2001-2023 The PHP Group
- My PHP.net
- Contact
- Other PHP.net sites
- Privacy policy