PHP: SplFileObject::fwrite - Manual (original) (raw)
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
SplFileObject::fwrite — Write to file
Parameters
data
The string to be written to the file.
length
If the length argument is given, writing will stop after length bytes have been written or the end of data is reached, whichever comes first.
Return Values
Returns the number of bytes written, or [false](reserved.constants.php#constant.false) on error.
Changelog
| Version | Description |
|---|---|
| 7.4.0 | The function now returns false instead of zero on failure. |
Examples
Example #1 SplFileObject::fwrite() example
<?php $file = new SplFileObject("fwrite.txt", "w"); <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>w</mi><mi>r</mi><mi>i</mi><mi>t</mi><mi>t</mi><mi>e</mi><mi>n</mi><mo>=</mo></mrow><annotation encoding="application/x-tex">written = </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6595em;"></span><span class="mord mathnormal" style="margin-right:0.02691em;">w</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord mathnormal">i</span><span class="mord mathnormal">tt</span><span class="mord mathnormal">e</span><span class="mord mathnormal">n</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>file->fwrite("12345"); echo "Wrote $written bytes to file"; ?>
The above example will output something similar to:
See Also
- fwrite() - Binary-safe file write
Found A Problem?
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...