Jump to: navigation, search

Php fprintf

From w3cyberlearnings

Contents

PHP function fprintf

This function writes a format string to a stream.

Syntax fprintf

  • stream is file handler, where to write/output the string.
  • format the string
  • arg1, arg2,arg3..

List of format

  •  %% - Returns a percent sign
  •  %b - Binary number
  •  %c - The character according to the ASCII value
  •  %d - Signed decimal number
  •  %e - Scientific notation (e.g. 1.2e+2)
  •  %u - Unsigned decimal number
  •  %f - Floating-point number (local settings aware)
  •  %F - Floating-point number (not local settings aware)
  •  %o - Octal number
  •  %s - String
  •  %x - Hexadecimal number (lowercase letters)
  •  %X - Hexadecimal number (uppercase letters)
fprintf(stream,format,arg1,arg2,arg++)

Example 1

<?php

$string1 = 'Exciting of science fiction:';
$id_number = 88;

$file_handler = fopen('test1.txt', 'w');
fprintf($file_handler, 'Title: %s, and Code: %u', $string1, $id_number);
fclose($file_handler);
// test and open for reading the file to get the result
$file_name = 'test1.txt';
$file_handler = fopen($file_name, 'r');
$file_data = fread($file_handler, 1024);
fclose($file_handler);
echo ($file_data);
?>

Output

Title: Exciting of science fiction:, and Code: 88

Example 2

<?php

$person_aa = array('John' => 20, 'Marry' => 20, 'Bob' => 40, 'Kat' => 100);

$file_handler = fopen('test1.txt', 'w');
foreach ($person_aa as $name => $salary) {
	fprintf($file_handler, 'Name: %s, Salary: %uK<br/>', $name, $salary);
}
fclose($file_handler);
// test and open for reading the file to get the result
$file_name = 'test1.txt';
$file_handler = fopen($file_name, 'r');
$file_data = fread($file_handler, 1024);
fclose($file_handler);
echo ($file_data);
?>

Output

Name: John, Salary: 20K
Name: Marry, Salary: 20K
Name: Bob, Salary: 40K
Name: Kat, Salary: 100K

Example 3

<?php
if (!($fp = fopen('date.txt', 'w'))) {
    return;
}

fprintf($fp, "%04d-%02d-%02d", date('Y'), date('m'), date('d'));
// will write the formatted ISO date to date.txt
?>

Related Functions


Navigation
Web
SQL
MISC
References