Hướng dẫn
Quảng cáo

Hàm vfprintf() trong PHP

Hướng dẫn cách sử dụng hàm vfprintf() trong lập trình PHP

Tác dụng của hàm vfprintf()

The vfprintf() function writes a formatted string to a stream, usually a file.

This function takes a special format string and then any number of other arguments, which will be formatted and spliced into the specified places in the format string to generate the result.

Related functions: fprintf(), printf(), sprintf(), vprintf() and vsprintf().

The following table summarizes the technical details of this function.

Return Value: Returns the length of the string written.
Version: PHP 5+

Syntax

The basic syntax of the vfprintf() function is given with:

vfprintf(stream, format, argument_array);

The following example shows the vfprintf() function in action.

<?php
$file = "data.txt";

// Open the file for writing
$handle = fopen($file, "w") or die("ERROR: Cannot open the file.");

// Sample array
$argarray = array("50", "United States");

// Defining the format string
$format = "There are %d states in the %s.";

// Formatting and write the string to file
$length = vfprintf($handle, $format, $argarray);

echo "Wrote $length bytes to data.txt";
?>

The output of the above example will look something like this:

Wrote 41 bytes to data.txt

And, the text written to the file "data.txt" will be:

There are 50 states in the United States.

In the above example, if the "data.txt" file doesn't exist PHP will automatically create it and write the data. But, if the "data.txt" file already exist, PHP will erase the contents of this file, if it has any, before writing the new data. See the tutorial on PHP file system to learn more about it.

Note: Every character in the format string will be written literally, except the % character and characters that immediately follow it. The % character indicates the beginning of a conversion specification, which specifies how to print the arguments that follow the format string.

Tip: The vfprintf() function is identical to fprintf(), with one exception. The vfprintf() function accepts an array of arguments, whereas the fprintf() accepts a list of arguments.


Parameters

The vfprintf() function accepts the following parameters.

Parameter Description
stream Required. Specifies a file system pointer resource that is typically created using fopen().
format Required. Specifies the format string. It is composed of ordinary characters (excluding %) and one or more conversion specifications.
argument_array Required. Specifies an array of arguments that is to be formatted and inserted at the positions of conversion specifications in the format string.

Conversion Specification Syntax

This section describes the syntax of conversion specification in the format string in detail.

A conversion specification begins with a percent symbol (%). You must include a conversion specification for each argument that is passed to the vfprintf() function after the format string.

Alternatively, you can use the argument number followed by a dollar sign (i.e. argnum$) to apply multiple conversion specifications in the format string to the same argument. It must come immediately after the percent sign (%), before any other specifiers. See more examples section.

A conversion specification typically has the following syntax:

%[argnum$][flags][width][.precision]specifier

argnum

An integer followed by a dollar sign $, to specify which number argument to treat in the conversion.

flags

The flags consist of one or more of the following characters:

Flag Description
+ Adds a plus sign before positive numbers. By default, only negative numbers are marked.
- Left-justify within the given field width; Right justification is the default.
(space) Pads the result with spaces. This is the default.
0 Only left-pads numbers with zeros. With s specifiers this can also right-pad with zeros.
'(char) Pads the result with the character (char). Must be used together with the width specifier.

width

An integer that indicates how many characters (minimum) this conversion should result in.

precision

A period (.) followed by an integer who's meaning depends on the specifier:

  • For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
  • For g and G specifiers: this is the maximum number of significant digits to be printed.
  • For s specifier: it acts as a cutoff point, setting a maximum character limit to the string.

If the period is specified without an explicit value for precision, 0 is assumed.

specifier

A single character indicating how the type of the argument should be interpreted.

specifier Description
% A literal percent character. No argument is required.
b The argument is treated as an integer and printed as a binary number.
c The argument is treated as an integer and printed as the character with that ASCII.
d The argument is treated as an integer and printed as a (signed) decimal number.
e The argument is treated as as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point.
E Like the e specifier but uses uppercase letter (e.g. 1.2E+2).
f The argument is treated as as a float and printed as a floating-point number (locale aware).
F The argument is treated as as a float and printed as a floating-point number (non-locale aware).
g General format. Uses e and f.
G Like the g specifier but uses E and f.
o The argument is treated as an integer and printed as an octal number.
s The argument is treated and printed as a string.
u The argument is treated as an integer and printed as an unsigned decimal number.
x The argument is treated as an integer and printed as a hexadecimal number (lowercase letters).
X The argument is treated as an integer and printed as a hexadecimal number (uppercase letters).

More Examples

Here're some more examples showing how vfprintf() function actually works:

The following example shows how to apply multiple conversion specifications to the same argument.

<?php
$file = "data.txt";

// Open the file for writing
$handle = fopen($file, "w") or die("ERROR: Cannot open the file.");

// Sample array
$array = array('star');

// Defining the format string
$format = 'The polar %1$s is the brightest %1$s in the sky.';

// Formatting and write the string to file
$length = vfprintf($handle, $format, $array);

echo "Wrote $length bytes to data.txt";
?>

The output of the above example will look something like this:

Wrote 48 bytes to data.txt

And, the text written to the file "data.txt" will be:

The polar star is the brightest star in the sky.

Tip: If the format string is enclosed in double-quotes (""), you need to escape the dollar sign after argnum with a backslash character (\), like this %1\$s, so that the PHP doesn't try to interpret them as variable. Using a backslash like this is called an escape sequence.

The following example shows how to format the same number with and without decimal points.

<?php
$file = "data.txt";

// Open the file for writing
$handle = fopen($file, "w") or die("ERROR: Cannot open the file.");

// Sample array
$array = array(499);

// Defining the format string
$format = "The number without decimal points: %1\$d, and the number with two decimal points: %1\$.2f";

// Formatting and write the string to file
$length = vfprintf($handle, $format, $array);

echo "Wrote $length bytes to data.txt";
?>

The output of the above example will look something like this:

Wrote 86 bytes to data.txt

And, the text written to the file "data.txt" will be:

The number without decimal points: 499, and the number with two decimal points: 499.00

By default, each conversion specification will be replaced by the formatted argument in the order they are listed inside the function. But, you can swap arguments inside the format string using argnum.

<?php
$file = "data.txt";

// Open the file for writing
$handle = fopen($file, "w") or die("ERROR: Cannot open the file.");

// Sample array
$array = array("50", "United States");

// Defining the format string
$format = "The %2\$s is a federal republic of %1\$d states.";

// Formatting and write the string to file
$length = vfprintf($handle, $format, $array);

echo "Wrote $length bytes to data.txt";
?>

The output of the above example will look something like this:

Wrote 53 bytes to data.txt

And, the text written to the file "data.txt" will be:

The United States is a federal republic of 50 states.

Tip: If the order of the placeholders or conversion specifications in the format string does not match the order of the arguments listed inside the function. You can use argnum to easily indicate which arguments the placeholders refer to and leave the function code as is.

The following example simply demonstrates what would be the possible outcome when using the different format specifiers for integer values using the printf() function.

<?php
// Sample integers
$num1 = 123456789;
$num2 = -123456789;
$num3 = 65; // ASCII 65 is 'A'

// Notice the double %%, this simply prints a '%' character
printf("%%b = %b <br>", $num1); // Binary representation
printf("%%c = %c <br>", $num3); // The ASCII Character
printf("%%d = %d <br>", $num1); // Standard integer representation
printf("%%d = %d <br>", $num2); // Standard integer representation
printf("%%e = %e <br>", $num1); // Scientific notation (lowercase)
printf("%%E = %E <br>", $num1); // Scientific notation (uppercase)
printf("%%u = %u <br>", $num1); // Unsigned integer representation (positive)
printf("%%u = %u <br>", $num2); // Unsigned integer representation (negative)
printf("%%f = %f <br>", $num1); // Floating-point representation (locale aware)
printf("%%F = %F <br>", $num1); // Floating-point representation (non-locale aware)
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); // Octal representation
printf("%%s = %s <br>", $num1); // String representation
printf("%%x = %x <br>", $num1); // Hexadecimal representation (lowercase)
printf("%%X = %X <br>", $num1); // Hexadecimal representation (uppercase)
printf("%%+d = %+d <br>", $num1); // Sign specifier (positive)
printf("%%+d = %+d <br>", $num2); // Sign specifier (negative)
?>

Similarly, the following example shows how to format a string in various ways using s specifier.

<?php
$str1 = "Hello";
$str2 = "Hello Alexander!";

printf("[%s]<br>", $str1);     // Standard string output
printf("[%10s]<br>", $str1);   // Right-justifies the string with spaces
printf("[%-10s]<br>", $str1);  // Left-justifies the string value with spaces
printf("[%010s]<br>", $str1);  // Left-pads string with zeros.
printf("[%-010s]<br>", $str1); // Right-pads string with zeros
printf("[%'#10s]<br>", $str1); // Left-pads string with '#' character
printf("[%.10s]<br>", $str2);  // Cuts off string after 10 characters
?>

Bài viết này đã giúp ích cho bạn?

Bài viết mới

Advertisements