PHP fprintf() 函数介绍
PHP fprintf() 函数介绍
代码示例
以下操作将部分文本内容保存至名为 "test.txt" 的文件中:
<?php
$number = 9;
$str = "Beijing";
$file = fopen("test.txt","w");
echo fprintf($file,"There are %u million bicycles in %s.",$number,$str);
?>
上述代码运行后产生的结果如下:
40
最终被写入到文件 "test.txt" 中的内容为:
There are 9 million bicycles in Beijing.
功能定义
fprintf()函数负责将格式化后的字符串写入到目标输出流中,常见的目标包括文件或数据库连接。
参数 arg1、arg2 及后续参数会依次填入主字符串中的百分号(%)位置。处理过程是逐步进行的:第一个 % 对应 arg1,第二个 % 对应 arg2,以此类推。
注意:当格式字符串中的 % 符号数量超过提供的参数时,必须使用占位符。占位符由数字和 "$" 组成,置于 % 符号之后,具体用法可参考实例 2。
提示:与之相关的函数包括 printf()、sprintf()、vprintf()、vsprintf() 以及 vfprintf()。
语法结构
fprintf( _stream,format,arg1,arg2,arg++_ )


示例一
实现向文件中写入文本的功能:
<?php
$number = 123;
$file = fopen("test.txt","w");
fprintf($file,"%f",$number);
?>
成功写入文件 "test.txt" 的内容如下:
123.000000
示例二
演示如何使用占位符控制参数顺序:
<?php
$number = 123;
$file = fopen("test.txt","w");
fprintf($file,"With 2 decimals: %1$.2f
nWith no decimals: %1$u",$number);
?>
写入文件 "test.txt" 的结果为:
With 2 decimals: 123.00 With no decimals: 123
示例三
利用 printf() 展示所有可用的格式值类型:
<?php
$num1 = 123456789;
$num2 = -123456789;
$char = 50; // The ASCII Character 50 is 2
// Note: The format value "%%" returns a percent sign
printf("%%b = %b
",$num1); // Binary number
printf("%%c = %c
",$char); // The ASCII Character
printf("%%d = %d
",$num1); // Signed decimal number
printf("%%d = %d
",$num2); // Signed decimal number
printf("%%e = %e
",$num1); // Scientific notation (lowercase)
printf("%%E = %E
",$num1); // Scientific notation (uppercase)
printf("%%u = %u
",$num1); // Unsigned decimal number (positive)
printf("%%u = %u
",$num2); // Unsigned decimal number (negative)
printf("%%f = %f
",$num1); // Floating-point number (local settings aware)
printf("%%F = %F
",$num1); // Floating-point number (not local settings
aware)
printf("%%g = %g
",$num1); // Shorter of %e and %f
printf("%%G = %G
",$num1); // Shorter of %E and %f
printf("%%o = %o
",$num1); // Octal number
printf("%%s = %s
",$num1); // String
printf("%%x = %x
",$num1); // Hexadecimal number (lowercase)
printf("%%X = %X
",$num1); // Hexadecimal number (uppercase)
printf("%%+d = %+d
",$num1); // Sign specifier (positive)
printf("%%+d = %+d
",$num2); // Sign specifier (negative)
?>
总结
以上就是本文的全部内容,希望能为各位的学习或工作提供参考价值,感谢对本站的支持。如需了解更多相关知识,请查阅下方相关链接。