phpxmlzipxmldom

How to unzip xml file using PHP


I have a zipped XML file on my PHP system.

How do I unzip it to load it into XMLDOM?

I only have one XML file per zip archive.

Thanks in advance.


Solution

  • You can use the php classes ZipArchive and DOMDocument i.e.:

    <?php
    //set the correct xml headers to output to browser
    header("Content-type: text/xml");
    $zipFile = "file.zip";
    $zip = new ZipArchive;
    if ($zip->open($zipFile))
    {
        //get the xml filename inside the zip
        $xmlFile =  $zip->getNameIndex(0); //you only  have 1 xml file iside of the zip
        $zip->close();
        //read the xml file inside the zip without extracting it to disk (memory)
        $xml = file_get_contents("zip://$zipFile#$xmlFile");
        //create a new document
        $dom = new DOMDocument('1.0', "UTF-8");
        //load teh xml file
        $dom->loadXML($xml);
        //Here you can  manipulate the XML dom , add, remove nodes, etc.
        //save and echo the XML
        echo $dom->saveXML();
    } else {
        echo 'zip open failed failed';
    }
    

    Notes:

    1. How do I ask a good question?
    2. I've tested the code with this xml file and it works as expected.