Php write out a file

PHP File Create/Write

In this chapter we will teach you how to create and write to a file on the server.

PHP Create File — fopen()

The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the same function used to open files.

If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).

The example below creates a new file called «testfile.txt». The file will be created in the same directory where the PHP code resides:

Example

PHP File Permissions

If you are having errors when trying to get this code to run, check that you have granted your PHP file access to write information to the hard drive.

PHP Write to File — fwrite()

The fwrite() function is used to write to a file.

The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.

The example below writes a couple of names into a new file called «newfile.txt»:

Example

$myfile = fopen(«newfile.txt», «w») or die(«Unable to open file!»);
$txt = «John Doe\n»;
fwrite($myfile, $txt);
$txt = «Jane Doe\n»;
fwrite($myfile, $txt);
fclose($myfile);
?>

Notice that we wrote to the file «newfile.txt» twice. Each time we wrote to the file we sent the string $txt that first contained «John Doe» and second contained «Jane Doe». After we finished writing, we closed the file using the fclose() function.

If we open the «newfile.txt» file it would look like this:

PHP Overwriting

Now that «newfile.txt» contains some data we can show what happens when we open an existing file for writing. All the existing data will be ERASED and we start with an empty file.

In the example below we open our existing file «newfile.txt», and write some new data into it:

Example

$myfile = fopen(«newfile.txt», «w») or die(«Unable to open file!»);
$txt = «Mickey Mouse\n»;
fwrite($myfile, $txt);
$txt = «Minnie Mouse\n»;
fwrite($myfile, $txt);
fclose($myfile);
?>

If we now open the «newfile.txt» file, both John and Jane have vanished, and only the data we just wrote is present:

Читайте также:  Content height auto html

PHP Append Text

You can append data to a file by using the «a» mode. The «a» mode appends text to the end of the file, while the «w» mode overrides (and erases) the old content of the file.

In the example below we open our existing file «newfile.txt», and append some text to it:

Example

$myfile = fopen(«newfile.txt», «a») or die(«Unable to open file!»);
$txt = «Donald Duck\n»;
fwrite($myfile, $txt);
$txt = «Goofy Goof\n»;
fwrite($myfile, $txt);
fclose($myfile);
?>

If we now open the «newfile.txt» file, we will see that Donald Duck and Goofy Goof is appended to the end of the file:

Complete PHP Filesystem Reference

For a complete reference of filesystem functions, go to our complete PHP Filesystem Reference.

Источник

fwrite

fwrite() writes the contents of data to the file stream pointed to by stream .

Parameters

A file system pointer resource that is typically created using fopen() .

The string that is to be written.

If length is an int , writing will stop after length bytes have been written or the end of data is reached, whichever comes first.

Return Values

fwrite() returns the number of bytes written, or false on failure.

Errors/Exceptions

fwrite() raises E_WARNING on failure.

Changelog

Examples

Example #1 A simple fwrite() example

$filename = ‘test.txt’ ;
$somecontent = «Add this to the file\n» ;

// Let’s make sure the file exists and is writable first.
if ( is_writable ( $filename ))

// In our example we’re opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that’s where $somecontent will go when we fwrite() it.
if (! $fp = fopen ( $filename , ‘a’ )) echo «Cannot open file ( $filename )» ;
exit;
>

// Write $somecontent to our opened file.
if ( fwrite ( $fp , $somecontent ) === FALSE ) echo «Cannot write to file ( $filename )» ;
exit;
>

echo «Success, wrote ( $somecontent ) to file ( $filename )» ;

> else echo «The file $filename is not writable» ;
>
?>

Notes

Note:

Writing to a network stream may end before the whole string is written. Return value of fwrite() may be checked:

function fwrite_stream ( $fp , $string ) for ( $written = 0 ; $written < strlen ( $string ); $written += $fwrite ) $fwrite = fwrite ( $fp , substr ( $string , $written ));
if ( $fwrite === false ) return $written ;
>
>
return $written ;
>
?>

Note:

On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with ‘b’ included in fopen() mode parameter.

Note:

If stream was fopen() ed in append mode, fwrite() s are atomic (unless the size of data exceeds the filesystem’s block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock() a resource before calling fwrite() ; all of the data will be written without interruption.

Note:

If writing twice to the file pointer, then the data will be appended to the end of the file content:

$fp = fopen ( ‘data.txt’ , ‘w’ );
fwrite ( $fp , ‘1’ );
fwrite ( $fp , ’23’ );
fclose ( $fp );

Читайте также:  Php админ панель шаблон

// the content of ‘data.txt’ is now 123 and not 23!
?>

See Also

  • fread() — Binary-safe file read
  • fopen() — Opens file or URL
  • fsockopen() — Open Internet or Unix domain socket connection
  • popen() — Opens process file pointer
  • file_get_contents() — Reads entire file into a string
  • pack() — Pack data into binary string

User Contributed Notes 33 notes

After having problems with fwrite() returning 0 in cases where one would fully expect a return value of false, I took a look at the source code for php’s fwrite() itself. The function will only return false if you pass in invalid arguments. Any other error, just as a broken pipe or closed connection, will result in a return value of less than strlen($string), in most cases 0.

Therefore, looping with repeated calls to fwrite() until the sum of number of bytes written equals the strlen() of the full value or expecting false on error will result in an infinite loop if the connection is lost.

This means the example fwrite_stream() code from the docs, as well as all the «helper» functions posted by others in the comments are all broken. You *must* check for a return value of 0 and either abort immediately or track a maximum number of retries.

Below is the example from the docs. This code is BAD, as a broken pipe will result in fwrite() infinitely looping with a return value of 0. Since the loop only breaks if fwrite() returns false or successfully writes all bytes, an infinite loop will occur on failure.

// BROKEN function — infinite loop when fwrite() returns 0s
function fwrite_stream ( $fp , $string ) <
for ( $written = 0 ; $written < strlen ( $string ); $written += $fwrite ) <
$fwrite = fwrite ( $fp , substr ( $string , $written ));
if ( $fwrite === false ) <
return $written ;
>
>
return $written ;
>
?>

$handles can also be used to output in console like below example

fwrite(STDOUT, «Console Output»);

Источник

Запись и чтение файлов в PHP

Примеры сохранения и чтения текстовых данных и массивов в файлы.

Сохранение в файл

Функция file_put_contents() записывает содержимое переменной в файл, если файла не существует. то пытается его создать, если существует то полностью перезапишет его.

File_put_contents:

$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'; $filename = __DIR__ . '/file.txt'; file_put_contents($filename, $text);

Fopen / fwrite:

Набор функций fopen, fwrite, fclose предназначены для более гибкой работы с файлами.

  • fopen – открытие или создание файла.
  • fwrite – запись данных.
  • fclose – закрытие файла.
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'; $filename = __DIR__ . '/file.txt'; $fh = fopen($filename, 'w'); fwrite($fh, $text); fclose($fh);

Возможные режимы fopen():

Mode Описание
r Открывает файл только для чтения, помещает указатель в начало файла.
r+ Открывает файл для чтения и записи, помещает указатель в начало файла.
w Открывает файл только для записи, помещает указатель в начало файла и обрезает файл до нулевой длины. Если файл не существует – пробует его создать.
w+ Открывает файл для чтения и записи, помещает указатель в начало файла и обрезает файл до нулевой длины. Если файл не существует – пытается его создать.
a Открывает файл только для записи, помещает указатель в конец файла. Если файл не существует – пытается его создать.
a+ Открывает файл для чтения и записи, помещает указатель в конец файла. Если файл не существует – пытается его создать.
x Создаёт и открывает только для записи; помещает указатель в начало файла. Если файл уже существует, вызов fopen() закончится неудачей, вернёт false и выдаст ошибку. Если файл не существует, попытается его создать.
x+ Создаёт и открывает для чтения и записи, в остальном имеет то же поведение, что и « x ».
c Открывает файл только для записи. Если файл не существует, то он создаётся. Если же файл существует, то он не обрезается (в отличие от « w »), и вызов к этой функции не вызывает ошибку (также как и в случае с « x »). Указатель на файл будет установлен на начало файла.
c+ Открывает файл для чтения и записи, в остальном имеет то же поведение, что и « c ».
Читайте также:  Java значения примитивных типов

Доступно в место fwrite() используют fputs() , разницы ни какой т.к. эта функция является псевдонимом.

Дописать строку в начало файла

$new_str = 'New line of text.'; $filename = __DIR__ . '/file.txt'; $text = file_get_contents($filename); file_put_contents($filename, $new_str . PHP_EOL . $text);

Дописать строку в конец файла

$new_str = 'New line of text.'; $filename = __DIR__ . '/file.txt'; file_put_contents($filename, PHP_EOL . $new_str, FILE_APPEND);
$new_str = 'New line of text.'; $filename = __DIR__ . '/file.txt'; $fh = fopen($filename, 'c'); fseek($fh, 0, SEEK_END); fwrite($fh, PHP_EOL . $new_str); fclose($fh);

Чтение из файла

Чтение всего файла

$filename = __DIR__ . '/file.txt'; $text = file_get_contents($filename); echo $text;
$filename = __DIR__ . '/file.txt'; $text = ''; $fh = fopen($filename, 'r'); while (!feof($fh)) < $line = fgets($fh); $text .= $line . PHP_EOL; >fclose($fh); echo $text;

Чтение файла в массив

Функция file() – читает содержимое файла и помещает его в массив, доступны опции:

  • FILE_IGNORE_NEW_LINES – пропускать новую строку в конце каждого элемента массива.
  • FILE_SKIP_EMPTY_LINES – пропускать пустые строки.
$filename = __DIR__ . '/file.txt'; $array = file($filename); print_r($array);

Чтение файла сразу в браузер

$filename = __DIR__ . '/file.txt'; readfile($filename);

Получить первую строку из файла

$filename = __DIR__ . '/file.txt'; $fh = fopen($filename, 'r'); echo fgets($fh); fclose($fh); /* или */ $filename = __DIR__ . '/file.txt'; $array = file($filename); echo $array[0];

Первые три строки из файла:

$filename = __DIR__ . '/file.txt'; $array = file($filename); $first_3 = array_slice($array, 0, 3); print_r($first_3);

Получить последнюю строку из файла

$filename = __DIR__ . '/file.txt'; $array = file($filename); $last = array_slice($array, -1); echo $last[0];

Последние три строки из файла:

$filename = __DIR__ . '/file.txt'; $array = file($filename); $last_3 = array_slice($array, -3); print_r($last_3);

Запись и чтение массивов в файл

Serialize

Не очень удачное хранение данных в сериализованном виде т.к. изменение одного символа может привести к ошибке чтения всех данных в файле. Подробнее в статье «Функция serialize, возможные проблемы»

Запись:

$array = array('foo', 'bar', 'hallo', 'world'); $text = base64_encode(serialize($array)); file_put_contents(__DIR__ . '/array.txt', $text);

Чтение:

$array = unserialize(base64_decode($text)); print_r($array);

JSON

Запись:

$array = array('foo', 'bar', 'hallo', 'world'); $json = json_encode($array, JSON_UNESCAPED_UNICODE); file_put_contents(__DIR__ . '/array.json', $json);

Чтение:

$json = file_get_contents(__DIR__ . '/array.json'); $array = json_decode($json, true); print_r($array);

Источник

Оцените статью