Open memory stream. Mode "r+" allows read and write.
Call fprintf twice. Each call appends more text.
Rewind the pointer. Needed before reading from the start.
Read the buffer.stream_get_contents returns the full text.
Frequently Asked Questions
fprintf() writes a formatted string to a stream (usually a file opened with fopen()). It uses the same format placeholders as sprintf() and printf(), but sends output to a stream instead of returning or echoing it.
int fprintf(resource $stream, string $format, mixed ...$values). Pass a stream from fopen(), a format string with placeholders like %s or %d, then the values to insert.
sprintf() returns the formatted string. fprintf() writes it to a stream and returns the number of bytes written. Use fprintf() for files; use sprintf() when you need the string in a variable.
An integer: how many bytes were written. On PHP 8+, invalid arguments typically throw instead of returning false.
Yes. Open php://memory with fopen('php://memory', 'r+') to write to an in-memory buffer, then read it back with rewind() and stream_get_contents().