- Stream Functions
- stream_filter_append
- Parameters
- Return Values
- Examples
- Notes
- See Also
- User Contributed Notes 5 notes
- 2 Ways To Write & Append To Files In PHP (Simple Examples)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- PHP WRITE FILE EXAMPLES
- EXAMPLE 1) WRITE TO FILES USING PUT CONTENTS
- EXAMPLE 2) WRITE & APPEND USING FOPEN
- EXAMPLE 3) ADDING NEW LINES
- EXAMPLE 4) WRITE ARRAY TO FILE, LINE-BY-LINE
- EXAMPLE 5) WRITING AN ARRAY TO CSV FILE
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- SUMMARY
- LINKS & REFERENCES
- TUTORIAL VIDEO
- INFOGRAPHIC CHEAT SHEET
- THE END
Stream Functions
I can’t find any real documentation on the quoted-printable-encode stream filter, but I’ve gathered info from several places. It seems there are 4 options that can be passed in the param array as in my other note on this subject:
line-length: integer, simply sets line length before a soft break is inserted
line-break-chars: Which char or chars to consider as a line break — note that «\r\n» will only match CRLF, not CR or LF, so make sure it matches your content.
binary: boolean, hex encodes all control chars, including spaces and line breaks, but leaves alphanumerics untouched
force-encode-first: Forcibly hex-encodes the first char on each line, even if it’s alphanumeric. This is useful for avoiding corruption in some incompetent mail servers, like Exchange.
As this article says, there is no quoted_printable_encode function() in PHP: http://www.zend.com/manual/filters.convert.php
However there is a stream filter for quoted printable encoding. Here’s an example function that produces output suitable for email and doesn’t explicitly use external files (though it might do for strings over 2Mb due to the nature of the temp stream type):
function quoted_printable_encode ( $string ) $fp = fopen ( ‘php://temp/’ , ‘r+’ );
$params = array( ‘line-length’ => 70 , ‘line-break-chars’ => «\r\n» );
stream_filter_append ( $fp , ‘convert.quoted-printable-encode’ , STREAM_FILTER_READ , $params );
fputs ( $fp , $string );
rewind ( $fp );
return stream_get_contents ( $fp );
>
echo quoted_printable_encode ( str_repeat ( «hello there » , 50 ). » a=1\r\n» ). «\n» ;
?>
The filter needs to be restricted to STREAM_FILTER_READ because by default it will get filtered both going into and out of the stream, and will thus get encoded twice.
It should be much faster than using a PHP implementation of the same thing, though note that this will only work in PHP 5.1+.
- Streams
- Introduction
- Installing/Configuring
- Predefined Constants
- Stream Filters
- Stream Contexts
- Stream Errors
- Examples
- php_user_filter
- streamWrapper
- Stream Functions
stream_filter_append
Adds filtername to the list of filters attached to stream .
Parameters
By default, stream_filter_append() will attach the filter to the read filter chain if the file was opened for reading (i.e. File Mode: r , and/or + ). The filter will also be attached to the write filter chain if the file was opened for writing (i.e. File Mode: w , a , and/or + ). STREAM_FILTER_READ , STREAM_FILTER_WRITE , and/or STREAM_FILTER_ALL can also be passed to the read_write parameter to override this behavior.
This filter will be added with the specified params to the end of the list and will therefore be called last during stream operations. To add a filter to the beginning of the list, use stream_filter_prepend() .
Return Values
Returns a resource on success or false on failure. The resource can be used to refer to this filter instance during a call to stream_filter_remove() .
false is returned if stream is not a resource or if filtername cannot be located.
Examples
Example #1 Controlling where filters are applied
/* Open a test file for reading and writing */
$fp = fopen ( ‘test.txt’ , ‘w+’ );?php
/* Apply the ROT13 filter to the
* write filter chain, but not the
* read filter chain */
stream_filter_append ( $fp , «string.rot13» , STREAM_FILTER_WRITE );/* Write a simple string to the file
* it will be ROT13 transformed on the
* way out */
fwrite ( $fp , «This is a test\n» );/* Back up to the beginning of the file */
rewind ( $fp );/* Read the contents of the file back out.
* Had the filter been applied to the
* read filter chain as well, we would see
* the text ROT13ed back to its original state */
fpassthru ( $fp );Notes
Note: When using custom (user) filters
stream_filter_register() must be called first in order to register the desired user filter to filtername .Note: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is appended to a stream, data in the internal buffers is processed through the new filter at that time. This differs from the behavior of stream_filter_prepend() .
Note: When a filter is added for read and write, two instances of the filter are created. stream_filter_append() must be called twice with STREAM_FILTER_READ and STREAM_FILTER_WRITE to get both filter resources.
See Also
- stream_filter_register() — Register a user defined stream filter
- stream_filter_prepend() — Attach a filter to a stream
- stream_get_filters() — Retrieve list of registered filters
User Contributed Notes 5 notes
Note that stream filters applied to STDOUT are not called when outputting via echo or print.
This is easily demonstrated with the standard ROT13 filter:
stream_filter_append ( STDOUT , «string.rot13» );print «Hello PHP\n» ;
// Prints «Hello PHP»fprintf ( STDOUT , «Hello PHP\n» );
// Prints «Uryyb CUC»
?>If you want to filter STDOUT, you may have better luck with an output buffering callback added via ob_start:
http://php.net/manual/en/function.ob-start.phpAt the time of this writing, there is an open PHP feature request to support echo and print for stream filters:
https://bugs.php.net/bug.php?id=30583While using compression filters on a large set of files during one script invocation i’ve got
Fatal error: Allowed memory size of xxx bytes exhausted
even when my max memory limit settings was insane high (128MB)Workaround is to remember to remove filter after work done with stream_filter_remove:
foreach( $lot_of_files as $filename )
<
$fp = fopen ( $filename , ‘rb’ );
$filter_params = array( ‘level’ => 2 , ‘window’ => 15 , $memory => 6 );
$s_filter = stream_filter_append ( $fp , ‘zlib.deflate’ , STREAM_FILTER_READ , $filter_params );
// here stream-operating codeThe difference betweem adding a stream filter first or last in the filte list in only the order they will be applied to streams.
For example, if you’re reading data from a file, and a given filter is placed in first place with stream_filter_prepend()the data will be processed by that filter first.
This example reads out file data and the filter is applied at the beginning of the reading operation:
/* Open a test file for reading */
$fp = fopen ( «test.txt» , «r» );
/* Apply the ROT13 filter to the
* read filter chain, but not the
* write filter chain */
stream_filter_prepend ( $fp , «string.rot13» ,
STREAM_FILTER_READ );
// read file data
$contents = fread ( $fp , 1024 );
// file data is first filtered and stored in $contents
echo $contents ;
fclose ( $fp );
?>On the other hand, if stream_filter_append() is used, then the filter will be applied at the end of the data operation. The thing about this is only the order filters are applied to streams. Back to the example, it’s not the same thing removing new lines from file data and then counting the number of characters, than performing the inverse process. In this case, the order that filters are applied to stream is important.
This example writes a test string to a file. The filter is applied at the end of the writing operation:
/* Open a test file for writing */
$fp = fopen ( «test.txt» , «w+» );
/* Apply the ROT13 filter to the
* write filter chain, but not the
* read filter chain */
stream_filter_append ( $fp , «string.rot13» ,
STREAM_FILTER_WRITE );
/* Write a simple string to the file
* it will be ROT13 transformed at the end of the
stream operation
* way out */
fwrite ( $fp , «This is a test\n» ); // string data is
first written , then ROT13 tranformed and lastly
written to file
/* Back up to the beginning of the file */
rewind ( $fp );
$contents = fread ( $fp , 512 );
fclose ( $fp );
echo $contents ;
?>In the first case, data is transformed at the end of the writing operation, while in the second one, data is first filtered and then stored in $contents.
2 Ways To Write & Append To Files In PHP (Simple Examples)
Welcome to a quick tutorial on how to write and append to files in PHP. Need to write some data to a file in your project?
- Write a string to a file.
- file_put_contents(«FILE.NAME», «DATA»);
- To append to an existing file, pass in an append flag – file_put_contents(«FILE.NAME», «DATA», FILE_APPEND);
- Open a file stream and write data to it.
- $fh = fopen(«FILE», «w») to create a new stream, or $fh = fopen(«FILE», «a») to append to an existing file.
- fwrite($fh, «STRING TO WRITE»);
- fclose($fh);
That should cover the quick basics, but read on if you need more examples!
TLDR – QUICK SLIDES
TABLE OF CONTENTS
PHP WRITE FILE EXAMPLES
All right, let us now go into the various examples of how to write files in PHP.
EXAMPLE 1) WRITE TO FILES USING PUT CONTENTS
Yep, this is the most convenient fuss-free way to write to file in PHP – Just use the file_put_contents() function. But take note that it will override the file by default, remember to pass in FILE_APPEND if you want to append to the file instead.
EXAMPLE 2) WRITE & APPEND USING FOPEN
- $fh = fopen(«demo.txt», «w») opens a file stream to work with. Take note of the second “mode” parameter – w stands for “write”m and a stands for “append”. But of course, there are a lot more, I will leave a link to the official PHP manual below if you are interested.
- fwrite($fh, «STRING») writes to the file.
- fclose($fh) closes the file stream. It is highly recommended to do so because nobody likes a corrupted file.
So why do some “dumb people” go through all the trouble to use this “inconvenient” method? Simply because it offers a lot more controls, and performs way better when dealing with massive amounts of data.
EXAMPLE 3) ADDING NEW LINES
// (A) OPEN/CREATE FILE - LOOP & WRITE $fh = fopen("demo.txt", "w"); // (B) WRITE LINES fwrite($fh, "First line.\r\n"); fwrite($fh, "Second line.\r\n"); fwrite($fh, "Third line.\r\n"); // (C) DONE fclose($fh); echo "DONE!";
- When it comes to adding new lines, there are 2 “special characters” that you have to know: \r for “carriage return” and \n for “line feed”.
- Then comes the painful part – Linux uses \n , Mac uses \r , Windows uses \r\n . Read on Wikipedia if you are interested.
- Most code ninjas just shrug and use \r\n regardless, and it is kind of “universally understood” as a single line break.
EXAMPLE 4) WRITE ARRAY TO FILE, LINE-BY-LINE
// (C) DONE fclose($fh); echo "DONE!";
- We open a file using fopen() as usual.
- Then simply use foreach() to loop through the array.
- Use fwrite() to write each element to the file, line-by-line.
- Lastly, close the file properly with fclose() .
EXAMPLE 5) WRITING AN ARRAY TO CSV FILE
// (C) DONE! fclose($fh); echo "DONE!";
Here is the last example, and a small extra for you guys who are looking to generate reports or spreadsheets. Yes, there is a fputcsv() function that we can conveniently use to create CSV files.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for this tutorial, and here is a small section on some extras and links that may be useful to you.
SUMMARY
LINKS & REFERENCES
TUTORIAL VIDEO
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end of this guide. I hope that this has helped you to better understand. If you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!