当前位置: 首页 > 网络学院 > 服务端脚本教程 > PHP > fprintf() 函数
The fprintf() function writes a formatted string to a specified output stream (example: file or database).
fprintf()函数的作用是:输出格式化字符串到流 / 将格式化后的字符串写到输出流。
The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works "step-by-step". At the first % sign, arg1 is inserted, at the second % sign, arg2 is inserted, etc.
arg1, arg2, ++参数将被插入到主体字符串中的百分号(%)之后。这个函数是“一步一步[step-by-step]”执行的。在第一个“%”之后插入arg1,在第二个“%”之后插入arg2,依次类推。
The fprintf() function returns the length of the written string.
fprintf()函数将返回书写的字符串长度。
fprintf(stream,format,arg1,arg2,arg++) |
Parameter参数 | Description描述 |
---|---|
stream | Required. Specifies where to write/output the string 必要参数。指定从哪个位置书写 / 输出字符串 |
format | Required. Specifies the string and how to format the variables in it. 必要参数。指定字符串,以及如何定义其中变量的格式。 Possible format values:
Additional format values. These are placed between the % and the letter (example %.2f):
Note: If multiple additional format values are used, they must be in the same order as above. |
arg1 | Required. The argument to be inserted at the first %-sign in the format string 必要参数。这个自变量(arg1)必须安插在第一个%-符号前 |
arg2 | Optional. The argument to be inserted at the second %-sign in the format string 可选参数。这个自变量(arg2)必须安插在第二个%-符号前 |
arg++ | Optional. The argument to be inserted at the third, fourth, etc. %-sign in the format string 可选参数。与上述自变量相同,它们可以安插在第三个、第四个……(依次类推)%-符号前。 |
Note: If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and "$". See example three.
注意:如果这里的%比自变量更多,你必须使用占位符[placeholders]。占位符是安插在%之后的,它是由自变量-数字和“$”组成的。具体可以见案例3。
Tip: Related functions: printf(), sprintf(), vfprintf(), vprintf(), and vsprintf().
提示:相关函数:printf(), sprintf(), vfprintf(), vprintf(), 和 vsprintf()
<?php $str = "Hello"; $number = 123; $file = fopen("test.txt","w"); echo fprintf($file,"%s world. Day number %u",$str,$number); ?> |
The output of the code above will be:
上述代码将输出下面的结果:
27 |
The following text will be written to the file "test.txt":
下面的文本将被写入文件“text.txt”:
Hello world. Day number 123 |
<?php $number = 123; $file = fopen("test.txt","w"); fprintf($file,"%f",$number); ?> |
The following text will be written to the file "test.txt":
下面的文本将被写入文件“text.txt”:
123.000000 |
Use of placeholders:
使用占位符
<?php $number = 123; $file = fopen("test.txt","w"); fprintf($file,"With 2 decimals: %1$.2f nWith no decimals: %1$u",$number); ?> |
The following text will be written to the file "test.txt":
下面的文本将被写入文件“text.txt”:
With 2 decimals: 123.00 With no decimals: 123 |