How PHP writes formatted strings to streams is a topic of concern to many developers. In PHP, you can use streams to write formatted strings to a specified file or output stream. Through appropriate file processing and output stream settings, the formatted string can be written to the stream in the specified encoding to achieve data output and storage. In this article, we will introduce how to implement this function in PHP to help developers better handle data output and storage needs.
PHP writes the formatted string to the stream
In php, you can use the printf()
function to write the formatted string into the stream. The printf()
function works similarly to the function of the same name in C language. It uses format specifiers to specify the format and representation of output variables.
grammar:
printf(fORMat, arg1, arg2, ..., argn);
in:
format
: A format string used to specify the output format and representation. argn
: Variable or expression to be written to the stream. Format specifier:
printf()
The function supports various format specifiers, which can be used to control the format, alignment and precision of output variables. The most commonly used format specifiers include:
%d
:Decimal integer%f
:Floating point number%s
:String%%
: Output the percent symbol itselfIn addition, you can use modifiers to further control the appearance of the output, for example:
: Add a positive sign in front of a positive number -
: left aligned output0
: pad the number with zeros.n
: Specify the number of decimal places for floating point numbersExample:
The following example demonstrates how to use the printf()
function to write a formatted string to a stream:
$name = "John Doe"; $age = 30; $salary = 120000; printf("Name: %s ", $name); printf("Age: %d ", $age); printf("Salary: $%.2f ", $salary);
Output:
Name: John Doe Age: 30 Salary: $120,000.00
Write string to stream:
In addition to using the printf()
function, you can also use the following methods to write strings to the stream:
fwrite()
: Write a string to the file handle. echo
: Output a string to standard output (usually a terminal window). print
: Output the string to standard output without wrapping. Example:
The following example demonstrates how to use the fwrite()
function to write a string to a file:
$file = fopen("output.txt", "w"); fwrite($file, "Hello, world! "); fclose($file);
The above is the detailed content of How to write formatted string to stream in PHP. For more information, please follow other related articles on the PHP Chinese website!