"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が挿入され、2番目の%記号ではarg2が挿入されます。
注: 引数よりも % 記号が多い場合は、プレースホルダを使用する必要があります。 プレースホルダは % 記号の後に挿入し、引数番号と "\$" で構成します。例2を参照してください。
チップ: 関連する関数: printf(), sprintf(), vprintf(), vsprintf() および vfprintf()
fprintf(stream,format,arg1,arg2,arg++)
パラメータ | 説明 |
---|---|
stream | 必須。文字列の書き出し/出力先を指定する |
format | 必須。文字列と、変数のフォーマット方法を指定する。 指定可能なフォーマット値:
フォーマットに追加指定できる値。これらは、%と文字の間に置きます (例 %.2f):
注: 複数の追加フォーマット値を使用する場合は、上と同じ順序でなければならない。 |
arg1 | 必須。フォーマット文字列の最初の%-signに挿入される引数 |
arg2 | 任意。フォーマット文字列の2番目の%-signに挿入される引数 |
arg++ | 任意。フォーマット文字列の3番目、4番目、等々の%-signに挿入される引数 |
返り値: | 書き出された文字列の長さを返します |
---|---|
PHP バージョン: | 5+ |
テキストをファイルに書き出します:
<?php
$number = 123;
$file = fopen("test.txt","w");
fprintf($file,"%f",$number);
?>
following text will be written to the file "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);
?>
following text will be written to the file "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
// 注: The format value "%%" パーセント記号を返す
printf("%%b = %b <br>",$num1); // 2進数
printf("%%c = %c <br>",$char); // The ASCII Character
printf("%%d = %d <br>",$num1); // 符号付き10進数
printf("%%d = %d <br>",$num2); // 符号付き10進数
printf("%%e = %e <br>",$num1); // Scientific notation (lowercase)
printf("%%E = %E <br>",$num1); // Scientific notation (uppercase)
printf("%%u = %u <br>",$num1); // 符号なし10進数 (positive)
printf("%%u = %u <br>",$num2); // 符号なし10進数 (negative)
printf("%%f = %f <br>",$num1); // 浮動小数点数(ロケールに依存する)
printf("%%F = %F <br>",$num1); // 浮動小数点数(ロケールに依存しない)
printf("%%g = %g <br>",$num1); // Shorter of %e and %f
printf("%%G = %G <br>",$num1); // Shorter of %E and %f
printf("%%o = %o <br>",$num1); // 8進数
printf("%%s = %s <br>",$num1); // String
printf("%%x = %x <br>",$num1); // Hexadecimal number (lowercase)
printf("%%X = %X <br>",$num1); // Hexadecimal number (uppercase)
printf("%%+d = %+d <br>",$num1); // Sign specifier (positive)
printf("%%+d = %+d <br>",$num2); // Sign specifier (negative)
?>
例の実行 »