Get contents of zip file php

ZipArchive::getFromName

The length to be read from the entry. If 0 , then the entire entry is read.

  • ZipArchive::FL_UNCHANGED
  • ZipArchive::FL_COMPRESSED
  • ZipArchive::FL_NOCASE

Return Values

Returns the contents of the entry on success or false on failure.

Examples

Example #1 Get the file contents

$zip = new ZipArchive ;
if ( $zip -> open ( ‘test1.zip’ ) === TRUE ) echo $zip -> getFromName ( ‘testfromfile.php’ );
$zip -> close ();
> else echo ‘failed’ ;
>
?>

Example #2 Convert an image from a zip entry

$z = new ZipArchive ();
if ( $z -> open ( dirname ( __FILE__ ) . ‘/test_im.zip’ )) $im_string = $z -> getFromName ( «pear_item.gif» );
$im = imagecreatefromstring ( $im_string );
imagepng ( $im , ‘b.png’ );
>
?>

See Also

User Contributed Notes 2 notes

The handling of file names containing non-ASCII characters is undocumented. It seems that this function calls and therefore expects DOS encoding in the zipfile but UTF-8 encoding for the name. If the zipfile uses UTF-8 names (Pkzip 4.5 / Winzip 11.2), this function fails. Use getFromIndex instead as a workaround.

When passing to the method explicit string which contains a relative path (inside the ZIP archive), e.g. ‘path/to/file.php/’ please make sure you used single quotation mark (‘) not the double one («). Double quotation mark produce FALSE (at least at Windows machine) giving no further hints what gone wrong.
Also, please make sure that the path delimiters used inside your ZIP file is backslash or forward slash since it’s make a difference in this place too.
I hope I saved you a headache while working with this (so far) unmentioned «feature» 🙂

  • ZipArchive
    • addEmptyDir
    • addFile
    • addFromString
    • addGlob
    • addPattern
    • clearError
    • close
    • count
    • deleteIndex
    • deleteName
    • extractTo
    • getArchiveComment
    • getArchiveFlag
    • getCommentIndex
    • getCommentName
    • getExternalAttributesIndex
    • getExternalAttributesName
    • getFromIndex
    • getFromName
    • getNameIndex
    • getStatusString
    • getStream
    • getStreamIndex
    • getStreamName
    • isCompressionMethodSupported
    • isEncryptionMethodSupported
    • locateName
    • open
    • registerCancelCallback
    • registerProgressCallback
    • renameIndex
    • renameName
    • replaceFile
    • setArchiveComment
    • setArchiveFlag
    • setCommentIndex
    • setCommentName
    • setCompressionIndex
    • setCompressionName
    • setEncryptionIndex
    • setEncryptionName
    • setExternalAttributesIndex
    • setExternalAttributesName
    • setMtimeIndex
    • setMtimeName
    • setPassword
    • statIndex
    • statName
    • unchangeAll
    • unchangeArchive
    • unchangeIndex
    • unchangeName

    Источник

    ZipArchive::getStream

    Get a file handler to the entry defined by its name. For now, it only supports read operations.

    Parameters

    The name of the entry to use.

    Return Values

    Returns a file pointer (resource) on success or false on failure.

    Examples

    Example #1 Get the entry contents with fread() and store it

    $contents = » ;
    $z = new ZipArchive ();
    if ( $z -> open ( ‘test.zip’ )) $fp = $z -> getStream ( ‘test’ );
    if(! $fp ) exit( «failed\n» );

    while (! feof ( $fp )) $contents .= fread ( $fp , 2 );
    >

    fclose ( $fp );
    file_put_contents ( ‘t’ , $contents );
    echo «done.\n» ;
    >
    ?>

    Example #2 Same as the previous example but with fopen() and the zip stream wrapper

    $contents = » ;
    $fp = fopen ( ‘zip://’ . dirname ( __FILE__ ) . ‘/test.zip#test’ , ‘r’ );
    if (! $fp ) exit( «cannot open\n» );
    >
    while (! feof ( $fp )) $contents .= fread ( $fp , 2 );
    >
    echo » $contents \n» ;
    fclose ( $fp );
    echo «done.\n» ;
    ?>

    Example #3 Stream wrapper and image, can be used with the xml function as well

    $im = imagecreatefromgif ( ‘zip://’ . dirname ( __FILE__ ) . ‘/test_im.zip#pear_item.gif’ );
    imagepng ( $im , ‘a.png’ );
    ?>

    See Also

    • ZipArchive::getStreamIndex() — Get a file handler to the entry defined by its index (read only)
    • ZipArchive::getStreamName() — Get a file handler to the entry defined by its name (read only)
    • Compression Streams

    User Contributed Notes 2 notes

    Here a way to handle specific files from a zip archive without full extract :

    $zip_file = ‘/path/to/file.zip’ ; // I wan to get stream a CSV files

    $zip = new ZipArchive ();
    $zip -> open ( $zip_file );
    for ( $i = 0 ; $i < $zip ->numFiles ; $i ++) < // Check file by file
    $name = $zip -> getNameIndex ( $i ); // Retrieve entry name
    $extension = pathinfo ( $name , PATHINFO_EXTENSION );
    if ( $extension === ‘csv’ ) < // I want to handle csv files
    $stream = $zip -> getStream ( $name ); // No stream index access before PHP 8.2
    // Starting PHP 8.2 $zip->getStreamIndex() or $zip->getStreamName()
    // Do stuff with $stream
    // .
    >
    >

    Источник

    How To Read Zip Files In PHP (Simple Examples)

    Welcome to a quick tutorial on how to read zip files in PHP. So the old zip functions are deprecated in PHP 8, how do we read files using Zip Archive then? This has caused some confusion, but it is actually very straightforward.

    To read zip files in PHP, we can use statIndex() to get the file statistics, and getFromName() to directly read a file.

    • $zip = new ZipArchive;
    • $zip->open(«FILE.ZIP», ZipArchive::RDONLY);
    • $entries = $zip->count();
    • for ($i=0; $istatIndex($i); >
    • $content = $zip->getFromName(«FILE-IN-ZIP.TXT»);
    • $zip->close();

    That should cover the basics, but if you need more concrete examples – Read on!

    TLDR – QUICK SLIDES

    How To Read Zip Files In PHP

    TABLE OF CONTENTS

    PHP READ ZIP FILE

    All right, let us now get into the examples of how to read a zip file in PHP.

    1) READ FILE LIST OR INFORMATION

    open($file, ZipArchive::RDONLY) !== true) < exit("Failed to open $file"); >// (B) LOOP THROUGH EVERY FILE & FOLDER - DISPLAY INFORMATION $total = $zip->count(); for ($i=0; $istatIndex($i)); > // (C) CLOSE ZIP $zip->close();

    This should be pretty self-explanatory, and how Zip Archive works is actually somewhat like an array – Each file or folder inside the zip archive will have an index number. To get a whole list of files/folders inside the archive, we can simply use a for loop to run through them and statIndex() to fetch the information.

    2) READ FILE IN ZIP ARCHIVE

    open($file, ZipArchive::RDONLY) !== true) < exit("Failed to open $file"); >// (B) DIRECTLY READ FILE USING INDEX $content = $zip->getFromIndex(0); echo "$content
    "; // (C) OR USE GET FROM FILE NAME $content = $zip->getFromName("second.txt"); echo "$content
    "; // (D) CLOSE ZIP $zip->close();

    To read the contents of a file inside a zip archive, we can either use getFromIndex() or getFromName() . But there will be a problem dealing with large files in this one. While both functions accept a second parameter to restrict the number of bytes read, there is just no way to open it as a file stream – The best way to deal with large files is still to unzip it and use fgets() instead.

    3) LEGACY ZIP READ

     // (B) READ FILES while ($entry = zip_read($zip)) < // (B1) GET FILE NAME & SIZE $name = zip_entry_name($entry); $size = zip_entry_filesize($entry); echo "$name - $size bytes
    "; // (B2) READ FILE DIRECTLY if ($name == "first.txt") < if (zip_entry_open($zip, $entry)) < $contents = zip_entry_read($entry); echo "$contents
    "; zip_entry_close($entry); > else < echo "Cannot open first.txt"; >> > zip_close($zip);

    Yes, the old zip functions are deprecated in PHP 8 (they still work but will eventually disappear). I shall not explain too much on this example but leave it here as “legacy support”… Do not use this method anymore, unless you have to support the older PHP versions.

    EXTRA) HOW TO UNZIP FILE

    open("TEST.ZIP") === TRUE) < $zip->extractTo("DESTINATION/FOLDER/"); $zip->close(); >

    DOWNLOAD & NOTES

    Here is the download link to the example code, so you don’t have to copy-paste everything.

    SUPPORT

    600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

    EXAMPLE CODE DOWNLOAD

    Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

    That’s all for the main tutorial, and here is a small section on some extras and links that may be useful to you.

    SUMMARY & REFERENCES

    INFOGRAPHIC CHEAT SHEET

    THE END

    Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

    Leave a Comment Cancel Reply

    Breakthrough Javascript

    Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!

    Socials

    About Me

    W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

    Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

    Источник

    Читайте также:  Qt moc cpp file
Оцените статью