PHP fprintf() function
Example
Write text to the text file named "test.txt":
<?php $number = 9; $str = "Beijing"; $file = fopen("test.txt","w"); echo fprintf($file,"There are 쥕lion bicycles in %s.",$number,$str); ?>
Output of the above code:
40
The following text will be written to the file "test.txt":
There are 9 million bicycles in Beijing.
Definition and usage
The fprintf() function writes the formatted string to the specified output stream (e.g., file or database):
arg1,arg2,arg++ Parameters will be inserted into the percentage sign (%) at the main string. The function is executed step by step. At the first % symbol, insert arg1, insert arg2, and so on.
注释:If the % symbol is more than arg If there are more parameters, you must use placeholders. Placeholders are inserted after the % symbol, consisting of numbers and "\$". See example 2.
Related functions:
Syntax
fprintf(stream,format,arg1,arg2,arg++)
Parameters | Description |
---|---|
stream | Required. Specifies where to write/output the string: |
format |
Required. Specifies the string and how to format the variables within it: Possible format values:
Additional format value. Must be placed between % and a letter (e.g., %.2f):
注释:如果使用多个额外的格式值,则必须按照上面的顺序进行使用。 |
arg1 | 必需。规定插到 format 字符串中第一个 %% 符号处的参数。 |
arg2 | 可选。规定插到 format 字符串中第二个 %% 符号处的参数。 |
arg++ | 可选。规定插到 format 字符串中第三、四等等 %% 符号处的参数。 |
技术细节
返回值: | 返回被写字符串的长度。 |
PHP 版本: | 5+ |
更多实例
例子 1
把文本写入文件中:
<?php $number = 123; $file = fopen("test.txt","w"); fprintf($file,"%%f",$number); ?>
下面的文本将被写入到文件 "test.txt":
123.000000
例子 2
使用占位符:
<?php $number = 123; $file = fopen("test.txt","w"); fprintf($file,"有两位小数:%1\$.2f \n没有小数:%1\$u",$number); ?>
下面的文本将被写入到文件 "test.txt":
有两位小数:123.00 没有小数:123
例子 3
使用 printf() 来演示所有可能的格式值:
<?php $num1 = 123456789; $num2 = -123456789; $char = 50; // ASCII 字符 50 是 2 // 注释:格式值 "%%" 返回百分号 printf("%%b = %%b <br>",$num1); // 二进制数 printf("%%c = %%c <br>",$char); // ASCII 字符 printf("%%d = %%d <br>",$num1); // 带符号的十进制数 printf("%%d = %%d <br>",$num2); // 带符号的十进制数 printf("%%e = %%e <br>",$num1); // 科学计数法(小写) printf("%%E = %%E <br>",$num1); // 科学计数法(大写) printf("%鑾u <br>",$num1); // Ongetekend decimaal (positief) printf("%鑾u <br>",$num2); // Ongetekend decimaal (negatief) printf("%%f = %f <br>",$num1); // Float (afhankelijk van lokale instellingen) printf("%%F = %F <br>",$num1); // Float (niet afhankelijk van lokale instellingen) printf("%%g = %g <br>",$num1); // Korter dan %e en %f printf("%%G = %G <br>",$num1); // Korter dan %E en %f printf("%%o = %o <br>",$num1); // Octaal printf("%%s = %s <br>",$num1); // String printf("%%x = %x <br>",$num1); // Hexadecimaal (kleine letters) printf("%%X = %X <br>",$num1); // Hexadecimaal (hoofdletters) printf("%%+d = %+d <br>",$num1); // Tekensymbool (positief) printf("%%+d = %+d <br>",$num2); // Tekensymbool (negatief) ?>