PHP ZipArchive addFromString() Function

The ZipArchive::addFromString() function is an inbuilt function in PHP that is used to add a file to the zip archive with its content.
Syntax:
bool ZipArchive::addFromString(
string $name,
string $content,
int $flags = ZipArchive::FL_OVERWRITE
)
Parameters: This function accepts three parameters as mentioned above and described below.
- $name: This parameter holds the name of the file.
- $content: This parameter holds the content that is used to create the entry. The content is used in a binary safe mode.
- $flags: This parameter holds the bitmask that consists of ZipArchive::FL_OVERWRITE, ZipArchive::FL_ENC_GUESS, ZipArchive::FL_ENC_UTF_8, and ZipArchive::FL_ENC_CP437.
Return Value: This function returns “true” on success and “false” on failure.
Example 1: In this example, we will create a file and add the string to the file using the PHP ZipArchive::addFromString() function.
PHP
<?php // Create a new ZipArchive class $zip = new ZipArchive; // Open a zip file $file = $zip->open('zambiatek.zip'); // If zip file is open if ($file === TRUE) { // Create new txt file and // add string to the file $zip->addFromString( 'GFG.txt', 'Welcome to zambiatek' ); // Close the opened file $zip->close(); echo 'File Added Successfully.'; } else { echo 'Failed to Adding file.'; } ?> |
Output:
Example 2: In this example, we will create multiple files and add the string to those files using PHP ZipArchive::addFromString() function.
PHP
<?php // Create a new ZipArchive class $zip = new ZipArchive; // Open a zip file $file = $zip->open('zambiatek.zip', ZipArchive::CREATE); // If zip file is open if ($file === TRUE) { // Create new txt file and // add string to the file $zip->addFromString( 'GFG1.txt', 'Welcome to zambiatek' ); $zip->addFromString( 'GFG2.txt', 'A computer science portal' ); $zip->addFromString( 'GFG3.txt', 'Welcome to zambiatek' ); // Close the opened file $zip->close(); echo 'File Added Successfully.'; } else { echo 'Failed to Add files.'; } ?> |
Output:
Reference: https://www.php.net/manual/en/ziparchive.addfromstring.php



