当前位置: 首页>>代码示例>>PHP>>正文


PHP ZipArchive::getFromIndex方法代码示例

本文整理汇总了PHP中ZipArchive::getFromIndex方法的典型用法代码示例。如果您正苦于以下问题:PHP ZipArchive::getFromIndex方法的具体用法?PHP ZipArchive::getFromIndex怎么用?PHP ZipArchive::getFromIndex使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ZipArchive的用法示例。


在下文中一共展示了ZipArchive::getFromIndex方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: docx_getTextFromZippedXML

function docx_getTextFromZippedXML($archiveFile, $contentFile, $cacheFolder, $debug)
{
    // Создаёт "реинкарнацию" zip-архива...
    $zip = new \ZipArchive();
    // И пытаемся открыть переданный zip-файл
    if ($zip->open($archiveFile)) {
        @mkdir($cacheFolder);
        $zip->extractTo($cacheFolder);
        // В случае успеха ищем в архиве файл с данными
        $xml = false;
        $xml2 = false;
        $file = $contentFile;
        if (($index = $zip->locateName($file)) !== false) {
            // Если находим, то читаем его в строку
            $content = $zip->getFromIndex($index);
            // После этого подгружаем все entity и по возможности include'ы других файлов
            $xml = \DOMDocument::loadXML($content, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
        }
        $file = 'word/_rels/document.xml.rels';
        if (($index = $zip->locateName($file)) !== false) {
            // Если находим, то читаем его в строку
            $content = $zip->getFromIndex($index);
            $xml2 = \DOMDocument::loadXML($content, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
            //@ - https://bugs.php.net/bug.php?id=41398 Strict Standards:  Non-static method DOMDocument::loadXML() should not be called statically
        }
        $zip->close();
        return array($xml, $xml2);
    }
}
开发者ID:akiyatkin,项目名称:files,代码行数:29,代码来源:Docx.php

示例2: parsePackage

 /**
  * Extract headers and readme.txt data from a ZIP archive that contains a plugin or theme.
  *
  * Returns an associative array with these keys:
  *  'type'   - Detected package type. This can be either "plugin" or "theme".
  * 	'header' - An array of plugin or theme headers. See get_plugin_data() or WP_Theme for details.
  *  'readme' - An array of metadata extracted from readme.txt. @see self::parseReadme()
  * 	'pluginFile' - The name of the PHP file where the plugin headers were found relative to the root directory of the ZIP archive.
  * 	'stylesheet' - The relative path to the style.css file that contains theme headers, if any.
  *
  * The 'readme' key will only be present if the input archive contains a readme.txt file
  * formatted according to WordPress.org readme standards. Similarly, 'pluginFile' and
  * 'stylesheet' will only be present if the archive contains a plugin or a theme, respectively.
  *
  * @param string $packageFilename The path to the ZIP package.
  * @param bool $applyMarkdown Whether to transform markup used in readme.txt to HTML. Defaults to false.
  * @return array Either an associative array or FALSE if the input file is not a valid ZIP archive or doesn't contain a WP plugin or theme.
  */
 public static function parsePackage($packageFilename, $applyMarkdown = false)
 {
     if (!file_exists($packageFilename) || !is_readable($packageFilename)) {
         return false;
     }
     //Open the .zip
     $zip = new ZipArchive();
     if ($zip->open($packageFilename) !== true) {
         return false;
     }
     //Find and parse the plugin or theme file and (optionally) readme.txt.
     $header = null;
     $readme = null;
     $pluginFile = null;
     $stylesheet = null;
     $type = null;
     for ($fileIndex = 0; $fileIndex < $zip->numFiles && (empty($readme) || empty($header)); $fileIndex++) {
         $info = $zip->statIndex($fileIndex);
         //Normalize filename: convert backslashes to slashes, remove leading slashes.
         $fileName = trim(str_replace('\\', '/', $info['name']), '/');
         $fileName = ltrim($fileName, '/');
         $fileNameParts = explode('.', $fileName);
         $extension = strtolower(end($fileNameParts));
         $depth = substr_count($fileName, '/');
         //Skip empty files, directories and everything that's more than 1 sub-directory deep.
         if ($depth > 1 || $info['size'] == 0) {
             continue;
         }
         //readme.txt (for plugins)?
         if (empty($readme) && strtolower(basename($fileName)) == 'readme.txt') {
             //Try to parse the readme.
             $readme = self::parseReadme($zip->getFromIndex($fileIndex), $applyMarkdown);
         }
         //Theme stylesheet?
         if (empty($header) && strtolower(basename($fileName)) == 'style.css') {
             $fileContents = substr($zip->getFromIndex($fileIndex), 0, 8 * 1024);
             $header = self::getThemeHeaders($fileContents);
             if (!empty($header)) {
                 $stylesheet = $fileName;
                 $type = 'theme';
             }
         }
         //Main plugin file?
         if (empty($header) && $extension === 'php') {
             $fileContents = substr($zip->getFromIndex($fileIndex), 0, 8 * 1024);
             $header = self::getPluginHeaders($fileContents);
             if (!empty($header)) {
                 $pluginFile = $fileName;
                 $type = 'plugin';
             }
         }
     }
     if (empty($type)) {
         return false;
     } else {
         return compact('header', 'readme', 'pluginFile', 'stylesheet', 'type');
     }
 }
开发者ID:tsynodinos,项目名称:wp-update-server,代码行数:76,代码来源:extension-meta.php

示例3: pm_analysePluginPackage

/**
 * Tim Hodson: renamed functions to avoid collisions.
 * 
 * Extract plugin headers and readme.txt data from a plugin's ZIP archive.
 * 
 * Returns an associative array with these keys:
 * 	'headers' - An array of plugin headers. See get_plugin_data() for details.
 *  'readme' - An array of metadata extracted from readme.txt. See parsePluginReadme() for details.
 * 	'pluginFile' - The name of the PHP file where the plugin headers were found; relative to the root directory of the ZIP archive.
 * 
 * The 'readme' key will only be present if the input archive contains a readme.txt file
 * formatted according to WordPress.org readme standards.
 * 
 * @uses parsePluginReadme()
 * @uses get_plugin_data()
 * 
 * @param string $packageFilename The path to the plugin's ZIP package.
 * @param bool $applyMarkdown Whether to transform markup used in readme.txt to HTML. Defaults to false.
 * @return array Associative array containing 'headers', 'readme' and 'pluginFile'. Returns FALSE if the input file is not a valid ZIP archive or doesn't contain a WP plugin.
 */
function pm_analysePluginPackage($packageFilename, $applyMarkdown = false)
{
    if (!file_exists($packageFilename) || !is_readable($packageFilename)) {
        return false;
    }
    //Open the .zip
    $zip = new ZipArchive();
    if ($zip->open($packageFilename) !== true) {
        return false;
    }
    //Find and parse the plugin file and readme.txt
    $header = null;
    $readme = null;
    $pluginFile = null;
    for ($fileIndex = 0; $fileIndex < $zip->numFiles && (empty($readme) || empty($header)); $fileIndex++) {
        $info = $zip->statIndex($fileIndex);
        $fileName = trim(str_replace('\\', '/', $info['name']), '/');
        //Backslashes to slashes, kill leading slashes.
        //readme.txt?
        if (empty($readme) && strtolower(basename($fileName)) == 'readme.txt') {
            //Try to parse the readme
            $readme = pm_parsePluginReadme($zip->getFromIndex($fileIndex), $applyMarkdown);
            continue;
            //Skip the rest of the checks.
        }
        //Plugin header?
        if (empty($header)) {
            //Skip directories and empty files
            if ($info['size'] == 0) {
                continue;
            }
            //We're only interested in PHP files
            $extension = end(explode('.', $fileName));
            if (strtolower($extension) != 'php') {
                continue;
            }
            //WordPress only looks for plugin files in the top or second level
            //of the directory tree, so we do the same.
            if (substr_count($fileName, '/') > 1) {
                continue;
            }
            //Try to read the header. WP only scans the first 8kiB, so we do the same.
            $fileContents = substr($zip->getFromIndex($fileIndex), 0, 8 * 1024);
            $header = pm_getPluginHeader($fileContents);
            if (!empty($header)) {
                $pluginFile = $fileName;
            }
        }
    }
    if (empty($pluginFile)) {
        return false;
    } else {
        return compact('header', 'readme', 'pluginFile');
    }
}
开发者ID:StudentLifeMarketingAndDesign,项目名称:krui-wp,代码行数:75,代码来源:plugin-meta.php

示例4: load

 private function load($file)
 {
     if (file_exists($file)) {
         $zip = new ZipArchive();
         if ($zip->open($file) === true) {
             //attempt to load styles:
             if (($styleIndex = $zip->locateName('word/styles.xml')) !== false) {
                 $stylesXml = $zip->getFromIndex($styleIndex);
                 $xml = simplexml_load_string($stylesXml);
                 $namespaces = $xml->getNamespaces(true);
                 $children = $xml->children($namespaces['w']);
                 foreach ($children->style as $s) {
                     $attr = $s->attributes('w', true);
                     if (isset($attr['styleId'])) {
                         $tags = array();
                         $attrs = array();
                         foreach (get_object_vars($s->rPr) as $tag => $style) {
                             $att = $style->attributes('w', true);
                             switch ($tag) {
                                 case "b":
                                     $tags[] = 'strong';
                                     break;
                                 case "i":
                                     $tags[] = 'em';
                                     break;
                                 case "color":
                                     //echo (String) $att['val'];
                                     $attrs[] = 'color:#' . $att['val'];
                                     break;
                                 case "sz":
                                     $attrs[] = 'font-size:' . $att['val'] . 'px';
                                     break;
                             }
                         }
                         $styles[(string) $attr['styleId']] = array('tags' => $tags, 'attrs' => $attrs);
                     }
                 }
                 $this->styles = $styles;
             }
             if (($index = $zip->locateName('word/document.xml')) !== false) {
                 // If found, read it to the string
                 $data = $zip->getFromIndex($index);
                 // Close archive file
                 $zip->close();
                 return $data;
             }
             $zip->close();
         } else {
             $this->errors[] = 'Could not open file.';
         }
     } else {
         $this->errors[] = 'File does not exist.';
     }
 }
开发者ID:rinteresting,项目名称:Docx-to-HTML,代码行数:54,代码来源:docx_reader.php

示例5: setHash

 /**
  * Sets the hash that is used to uniquely identify this plugin
  */
 public function setHash()
 {
     $archiveName = $this->getFilenameOnFilestore();
     $zip = new ZipArchive();
     $result = $zip->open($archiveName);
     if ($result !== true) {
         return false;
     }
     for ($i = 0; $i < $zip->numFiles; $i++) {
         $filename = $zip->getNameIndex($i);
         if (stripos($filename, 'manifest.xml') !== false) {
             $manifest = $zip->getFromIndex($i);
             $id = substr($filename, 0, strpos($filename, '/'));
             break;
         }
     }
     $zip->close();
     if (!isset($manifest)) {
         return false;
     }
     try {
         $manifest = new ElggPluginManifest($manifest);
         $author = $manifest->getAuthor();
         $version = $manifest->getVersion();
         $this->hash = md5($id . $version . $author);
     } catch (Exception $e) {
         // skip invalid manifests
     }
 }
开发者ID:lorea,项目名称:Hydra-dev,代码行数:32,代码来源:PluginRelease.php

示例6: getListFormatting

 /**
  * grabs formatting for list styles from a related internal data file
  *
  * @param  SimpleXMLElement $numPr the list object element
  * @return array                   wrapping tags for ordered and unordered lists
  */
 private function getListFormatting($numPr)
 {
     $id = $numPr->numId->attributes('w', TRUE)['val'];
     $level = $numPr->ilvl->attributes('w', TRUE)['val'];
     if (FALSE !== ($index = $this->zip->locateName('word/numbering.xml'))) {
         $xml = $this->zip->getFromIndex($index);
         $doc = new DOMDocument();
         $doc->preserveWhiteSpace = FALSE;
         $doc->loadXML($xml);
         $xpath = new DOMXPath($doc);
         $nodes = $xpath->query('/w:numbering/w:num[@w:numId=' . $id . ']/w:abstractNumId');
         if ($nodes->length) {
             $id = $nodes->item(0)->getAttribute('w:val');
             $nodes = $xpath->query('/w:numbering/w:abstractNum[@w:abstractNumId=' . $id . ']/w:lvl[@w:ilvl=' . $level . ']/w:numFmt');
             if ($nodes->length) {
                 $listFormat = $nodes->item(0)->getAttribute('w:val');
                 if ($listFormat === 'bullet') {
                     return ['<ul>', '</ul>'];
                 } else {
                     if ($listFormat === 'decimal') {
                         return ['<ol>', '</ol>'];
                     }
                 }
             }
         }
     }
     return ['<ul class="list-unstyled">', '</ul>'];
 }
开发者ID:sophia2152,项目名称:DocX2HtmlParser,代码行数:34,代码来源:DocX2HtmlParser.php

示例7: readZippedXML

function readZippedXML($archiveFile, $dataFile)
{
    if (!class_exists('ZipArchive', false)) {
        return "ZipArchive Class Doesn't Exist.";
    }
    // Create new ZIP archive
    $zip = new ZipArchive();
    // Open received archive file
    if (true === $zip->open($archiveFile)) {
        // If done, search for the data file in the archive
        if (($index = $zip->locateName($dataFile)) !== false) {
            // If found, read it to the string
            $data = $zip->getFromIndex($index);
            // Close archive file
            $zip->close();
            // Load XML from a string
            // Skip errors and warnings
            return $data;
            //            $xml = DOMDocument::loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
            //            // Return data without XML formatting tags
            //            return strip_tags($xml->saveXML());
        }
        $zip->close();
    }
    // In case of failure return empty string
    return $zip->getStatusString();
}
开发者ID:GettyScholarsWorkspace,项目名称:GettyScholarsWorkspace,代码行数:27,代码来源:docx.php

示例8: locateFile

 private function locateFile(\ZipArchive $zip, $filename)
 {
     $indexOfShortestMatch = false;
     $lengthOfShortestMatch = -1;
     for ($i = 0; $i < $zip->numFiles; $i++) {
         $stat = $zip->statIndex($i);
         if (strcmp(basename($stat['name']), $filename) === 0) {
             $directoryName = dirname($stat['name']);
             if ($directoryName == '.') {
                 return $i;
             }
             if (strpos($directoryName, '\\') !== false || strpos($directoryName, '/') !== false) {
                 continue;
             }
             $length = strlen($stat['name']);
             if ($indexOfShortestMatch == false || $length < $lengthOfShortestMatch) {
                 $contents = $zip->getFromIndex($i);
                 if ($contents !== false) {
                     $indexOfShortestMatch = $i;
                     $lengthOfShortestMatch = $length;
                 }
             }
         }
     }
     return $indexOfShortestMatch;
 }
开发者ID:VicDeo,项目名称:poc,代码行数:26,代码来源:ArtifactRepository.php

示例9: retrieveResponse

 protected function retrieveResponse()
 {
     if (!class_exists('ZipArchive')) {
         throw new KurogoException("class ZipArchive (php-zip) not available");
     }
     $tmpFile = Kurogo::tempFile();
     // this is the same as parent
     if (!($this->requestURL = $this->url())) {
         throw new KurogoDataException("URL could not be determined");
     }
     $this->requestParameters = $this->parameters();
     // the following are private functions in URLDataRetriever
     //$this->requestMethod = $this->setContextMethod();
     //$this->requestHeaders = $this->setContextHeaders();
     //$this->requestData = $this->setContextData();
     Kurogo::log(LOG_INFO, "Retrieving {$this->requestURL}", 'url_retriever');
     // the creation of $data is different from parent
     copy($this->requestURL, $tmpFile);
     $zip = new ZipArchive();
     $zip->open($tmpFile);
     $data = $zip->getFromIndex(0);
     unlink($tmpFile);
     // this is the same as parent
     $http_response_header = isset($http_response_header) ? $http_response_header : array();
     $response = $this->initResponse();
     $response->setRequest($this->requestMethod, $this->requestURL, $this->requestParameters, $this->requestHeaders, null);
     $response->setResponse($data);
     $response->setResponseHeaders($http_response_header);
     Kurogo::log(LOG_DEBUG, sprintf("Returned status %d and %d bytes", $response->getCode(), strlen($data)), 'url_retriever');
     return $response;
 }
开发者ID:nncsang,项目名称:Kurogo,代码行数:31,代码来源:KMZDataRetriever.php

示例10: getPluginMeta

 /**
  * Retrieve plugin info from meta.json in zip
  * @param $zipPath
  * @return bool|mixed
  * @throws CakeException
  */
 public function getPluginMeta($zipPath)
 {
     $Zip = new \ZipArchive();
     if ($Zip->open($zipPath) === true) {
         $search = 'config/meta.json';
         $indexJson = $Zip->locateName('meta.json', \ZipArchive::FL_NODIR);
         if ($indexJson === false) {
             throw new Exception(__d('spider', 'Invalid meta information in archive'));
         } else {
             $fileName = $Zip->getNameIndex($indexJson);
             $fileJson = json_decode($Zip->getFromIndex($indexJson));
             if (empty($fileJson->name)) {
                 throw new Exception(__d('spider', 'Invalid meta.json or missing plugin name'));
             } else {
                 $pluginRootPath = str_replace($search, '', $fileName);
                 $fileJson->rootPath = $pluginRootPath;
             }
         }
         $Zip->close();
         if (!isset($fileJson) || empty($fileJson)) {
             throw new Exception(__d('spider', 'Invali meta.json'));
         }
         return $fileJson;
     } else {
         throw new CakeException(__d('spider', 'Invalid zip archive'));
     }
     return false;
 }
开发者ID:mohammadsaleh,项目名称:spider,代码行数:34,代码来源:PluginInstaller.php

示例11: getZipContent

 /**
  * Give it a path to a file and it will return
  * the contents of that file, either as xml or html
  *
  * @param string $file
  * @param bool $as_xml (optional)
  *
  * @return boolean|\DOMDocument
  */
 protected function getZipContent($file, $as_xml = true)
 {
     // Locates an entry using its name
     $index = $this->zip->locateName($file);
     if (false === $index) {
         return false;
     }
     // returns the contents using its index
     $content = $this->zip->getFromIndex($index);
     // if it's not xml, return
     if (!$as_xml) {
         return $content;
     }
     $collapsed = preg_replace('/\\s+/', '', $content);
     if (preg_match('/<!DOCTYPE/i', $collapsed)) {
         // Invalid XML: Detected use of illegal DOCTYPE
         return false;
     }
     // trouble with simplexmlelement and elements with dashes
     // (ODT's are ripe with dashes), so giving it to the DOM
     $old_value = libxml_disable_entity_loader(true);
     $xml = new \DOMDocument();
     $xml->loadXML($content, LIBXML_NOBLANKS | LIBXML_NOENT | LIBXML_NONET | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
     libxml_disable_entity_loader($old_value);
     return $xml;
 }
开发者ID:pressbooks,项目名称:pressbooks,代码行数:35,代码来源:class-pb-docx.php

示例12: loadFromFile

 public function loadFromFile($loc, $loadAllVars = false)
 {
     $this->source = $loc;
     $this->loadAllVars = $loadAllVars;
     if (file_exists($loc)) {
         if (preg_match('/\\.(gz|zip)$/i', $loc, $ext)) {
             switch (strtolower($ext[1])) {
                 case 'gz':
                     $loc = 'compress.zlib://' . $loc;
                     break;
                 case 'zip':
                     $zip = new ZipArchive();
                     if ($zip->open($loc) === true && $zip->numFiles == 1) {
                         return $this->loadFromString($zip->getFromIndex(0), $loadAllVars);
                     } else {
                         $loc = 'zip://' . $loc;
                     }
                     break;
             }
         }
         libxml_use_internal_errors(true);
         $xmlObj = @simplexml_load_file($loc);
         if ($this->isValidNzb($xmlObj)) {
             $this->parseNzb($xmlObj);
         }
         unset($xmlObj);
     }
     return $this->isLoaded;
 }
开发者ID:RickDB,项目名称:newznab-tmux,代码行数:29,代码来源:NZBInfo.php

示例13: getBootstrap

 /**
  * @return bool
  */
 public function getBootstrap()
 {
     if ($this->hasBootstrap()) {
         return $this->_zip->getFromIndex($this->_getBootstrapIndex());
     }
     return null;
 }
开发者ID:jasmun,项目名称:Noco100,代码行数:10,代码来源:Archive.php

示例14: extracttext

function extracttext($filename)
{
    //Check for extension
    //$ext = end(explode('.', $filename));
    //if its docx file
    //if($ext == 'docx')
    $dataFile = "word/document.xml";
    //else it must be odt file
    //else
    //$dataFile = "content.xml";
    //Create a new ZIP archive object
    $zip = new ZipArchive();
    // Open the archive file
    if (true === $zip->open($filename)) {
        // If successful, search for the data file in the archive
        if (($index = $zip->locateName($dataFile)) !== false) {
            // Index found! Now read it to a string
            $text = $zip->getFromIndex($index);
            // Load XML from a string
            // Ignore errors and warnings
            $xml = DOMDocument::loadXML($text, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
            // Remove XML formatting tags and return the text
            return strip_tags($xml->saveXML());
        }
        //Close the archive file
        $zip->close();
    }
    // In case of failure return a message
    return "File not found";
}
开发者ID:richardneal,项目名称:Lexomics,代码行数:30,代码来源:uploader.php

示例15: readZipPart

 /**
  * READS The Document and Relationships into separated XML files
  * 
  * @param String $filename The filename
  * @return void
  */
 private function readZipPart($filename)
 {
     $zip = new ZipArchive();
     $_xml = 'word/document.xml';
     $_xml_rels = 'word/_rels/document.xml.rels';
     if (true === $zip->open($filename)) {
         if (($index = $zip->locateName($_xml)) !== false) {
             $xml = $zip->getFromIndex($index);
         }
         $zip->close();
     } else {
         die('non zip file');
     }
     if (true === $zip->open($filename)) {
         if (($index = $zip->locateName($_xml_rels)) !== false) {
             $xml_rels = $zip->getFromIndex($index);
         }
         $zip->close();
     } else {
         die('non zip file');
     }
     $this->doc_xml = new DOMDocument();
     $this->doc_xml->encoding = mb_detect_encoding($xml);
     $this->doc_xml->preserveWhiteSpace = false;
     $this->doc_xml->formatOutput = true;
     $this->doc_xml->loadXML($xml);
     $this->doc_xml->saveXML();
     $this->rels_xml = new DOMDocument();
     $this->rels_xml->encoding = mb_detect_encoding($xml);
     $this->rels_xml->preserveWhiteSpace = false;
     $this->rels_xml->formatOutput = true;
     $this->rels_xml->loadXML($xml_rels);
     $this->rels_xml->saveXML();
     if ($this->debug) {
         echo "<textarea style='width:100%; height: 200px;'>";
         echo $this->doc_xml->saveXML();
         echo "</textarea>";
         echo "<textarea style='width:100%; height: 200px;'>";
         echo $this->rels_xml->saveXML();
         echo "</textarea>";
     }
 }
开发者ID:t-web,项目名称:wordphp,代码行数:48,代码来源:class.wordphp.php


注:本文中的ZipArchive::getFromIndex方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。