Friday, October 10, 2025
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
32349 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6715 POSTS0 COMMENTS
Nicole Veronica
11878 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6837 POSTS0 COMMENTS
Ted Musemwa
7097 POSTS0 COMMENTS
Thapelo Manthata
6792 POSTS0 COMMENTS
Umr Jansen
6791 POSTS0 COMMENTS