fprintf လုပ်ဆောင်ချက်
fprintf လုပ်ဆောင်ချက်သည် ဖော်ပြထားသော template အလိုက် string ကို format ချပြီး ရလဒ်ကို ဖိုင်လမ်းကြောင်း resource တစ်ခုသို့ ရေးသည်။ ပထမဆုံး parameter အနေဖြင့် ဖိုင်လမ်းကြောင်း resource ကိုလက်ခံပြီး၊ ဒုတိယ parameter အနေဖြင့် format string ကိုလက်ခံကာ၊ နောက်ဆက်တွဲ parameters များသည် template အတွင်း အစားထိုးရန် တန်ဖိုးများဖြစ်သည်။ ဖိုင်လမ်းကြောင်း resource အစား null ကိုပေးလျှင်၊ လုပ်ဆောင်ချက်သည် stream သို့ရေးမည့်အစား string ကို ပြန်ပေးသည်။
Format string အတွင်း ထူးခြားသော သင်္ကေတများ (format specifiers) ကိုအသုံးပြုသည်။ ၎င်းတို့သည် % သင်္ကေတဖြင့်စတင်ကာ output ၏ formatting ကိုထိန်းချုပ်ပေးသည်။
Syntax
fprintf(resource $handle, string $format, mixed ...$values): int|false
Format Specifiers
| Specifier | ဖော်ပြချက် |
|---|---|
%s |
String |
%d |
Signed integer (decimal) |
%u |
Unsigned integer (decimal) |
%f |
Floating-point number (locale aware) |
%F |
Floating-point number (non-locale aware) |
%c |
ASCII code ဖြင့် Character |
%x |
Integer in hexadecimal (lowercase) |
%X |
Integer in hexadecimal (uppercase) |
%o |
Integer in octal |
%b |
Integer in binary |
%e |
Scientific notation (lowercase) |
%E |
Scientific notation (uppercase) |
%g |
Shorter of %e or %f |
%G |
Shorter of %E or %F |
%% |
Percent sign |
ဥပမာ
Format ချထားသော string ကို ဖိုင်တစ်ခုထဲသို့ရေးခြင်း:
<?php
$file = fopen('output.txt', 'w');
fprintf($file, "Name: %s, Age: %d", "John", 25);
fclose($file);
?>
output.txt ဖိုင်တွင် ပါဝင်သည့် အကြောင်းအရာ:
'Name: John, Age: 25'
ဥပမာ
Format specifiers အမျိုးမျိုးကို အသုံးပြုခြင်း:
<?php
$res = fopen('php://temp', 'w');
fprintf($res, "Float: %.2f, Hex: %x", 12.3456, 255);
rewind($res);
echo stream_get_contents($res);
fclose($res);
?>
ကုဒ် run ပြီးနောက် ရရှိသော ရလဒ်:
'Float: 12.35, Hex: ff'
ဥပမာ
ဖိုင်ထဲသို့ရေးမည့်အစား string အနေဖြင့် ပြန်ပေးခြင်း:
<?php
$result = sprintf("Today is %s", date('Y-m-d'));
echo $result;
?>
ကုဒ် run ပြီးနောက် ရရှိသော ရလဒ်:
'Today is 2023-11-15'
ဤအကြောင်းကိုလည်း ကြည့်ပါ
-
sprintfလုပ်ဆောင်ချက်,
သည် format ချထားသော string ကို ပြန်ပေးသည် -
vprintfလုပ်ဆောင်ချက်,
သည် format ချထားသော string ကို output ထုတ်ပေးသည် -
file_put_contentsလုပ်ဆောင်ချက်,
သည် data များကို ဖိုင်တစ်ခုထဲသို့ ရေးပေးသည်