SplFileObject::fwrite

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::fwriteファイルに書き込む

説明

public SplFileObject::fwrite(string $data, ?int $length = null): int|false

Writes the contents of data to the file

パラメータ

data

ファイルに書き込まれる文字列。

length

length 引数が int の場合、length バイト分だけ書き込まれた後もしくは data の終端に達するのどちらか早い方の後で書き込みが停止します。

戻り値

書き込まれるバイト数、もしくはエラーの場合 false を返します。

変更履歴

バージョン 説明
8.5.0 length は nullable になりました。
7.4.0 この関数は、失敗した時に0ではなく false を返すようになりました。

例1 SplFileObject::fwrite() の例

<?php
$file
= new SplFileObject("fwrite.txt", "w");
$written = $file->fwrite("12345");
echo
"$written バイトをファイルに書き込みました";
?>

上の例の出力は、 たとえば以下のようになります。

Wrote 5 bytes to file

参考

  • fwrite() - バイナリセーフなファイル書き込み処理

add a note

User Contributed Notes 1 note

up
15
bas dot hilbers at tribal-im dot com
12 years ago
Your \SplFileObject will not throw an exception when trying to write to a non-writeable stream!

I forgot to set the second parameter on my \SplFileObject constructor (the mode), costing me minutes to figure out why nothing was written by the fwrite method...
To Top