Tuesday, June 9, 2026
HomeLanguagesPHP ZipArchive addFromString() Function

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('neveropen.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 neveropen'
        );
  
        // 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('neveropen.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 neveropen'
        );
  
        $zip->addFromString(
            'GFG2.txt'
            'A computer science portal'
        );
  
        $zip->addFromString(
            'GFG3.txt'
            'Welcome to neveropen'
        );
  
        // 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

RELATED ARTICLES

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6895 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7018 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS