当前位置:  编程技术>php
本页文章导读:
    ▪php xml分析类的实例代码      php实现的xml文件分析类。 代码:   代码示例: <?php /** * xml节点类 */ class Node {     var $name;     var $attributes;     var $ancestors = "/"     var $data;     var $type;       function Node($t.........
    ▪php打包一组文件为zip压缩包的类      php zip文件压缩类: 添加文件到数组,最后将添加的文件打包成zip。 代码:   代码示例: <?php /** * Zip file creation class. * Makes zip files. * * @access  public */ class zipfile {     /**      * A.........
    ▪php导出CSV文件的实现代码      php导出CSV文件,供Excel读取。 代码:   代码示例: <?php // 注意包含正确的类路径 require_once(dirname(__FILE__) . '/export.php'); $exceler= newJason_Excel_Export();   // 生成excel格式 这里根据后缀名不.........

[1]php xml分析类的实例代码
    来源: 互联网  发布时间: 2013-12-24

php实现的xml文件分析类。
代码:
 

代码示例:
<?php
/**
* xml节点类
*/
class Node {
    var $name;
    var $attributes;
    var $ancestors = "/"
    var $data;
    var $type;
 
    function Node($tree) {
        $this->name = array_pop($tree);
        $this->ancestors .= implode("/", $tree);
    }
 
    function add_data($value) {
        $this->data .= ' '.$value;
    }
 
    function get_type() {
        if (strlen($this->data) > 0) {
            return "with CDATA"
        } else {
            return "without CDATA"
        }
    }
 
    function level() {
        if ($this->ancestors == "/") return 0;
      if (preg_match_all("/(\/{1})/", $this->ancestors, $result,PREG_PATTERN_ORDER)) {
        return (count($result[0]));
      } else {
        return 0;
        }
    }
 
    function has_attributes() {
        return (is_array($this->attributes));
    }
 
    function print_name() {
        return "$this->name";
    }
 
    function is_child($node) {
        $result = preg_match("/^$ancestors/", $node->ancestors, $match);
        if ($node->ancestors == $this->ancestors) $result = false;
        return $result;
    }
}
/**
* xml分析类
*/
class XML {
    var $file;
    var $tree = array();
    var $nodes = array();
    var $PIs;
    var $format_body = "font-family:Verdana;font-size:10pt;"
    var $format_bracket = "color:blue;"
    var $format_element = "font-family:Verdana;font-weight:bold;font-size:10pt;"
    var $format_attribute = "font-family:Courier;font-size:10pt;"
    var $format_data = "font-size:12pt;"
    var $format_attribute_name = "color:#444444;"
    var $format_attribute_value = "font-family:Courier;font-size:10pt;color:red;"
    var $format_blanks = "   "
 
    function XML($filename) {
        $this->file = $filename;
        $xml_parser = xml_parser_create();
        xml_set_object($xml_parser,&$this);
        xml_set_element_handler($xml_parser, "startElement", "endElement");
        xml_set_character_data_handler($xml_parser, "characterData");
        xml_set_processing_instruction_handler ($xml_parser, "process_instruction");
                # Why should one want to use case-folding with XML? XML is case-sensitiv, I think this is nonsense
        xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false);
 
        if (!($fp = @fopen($this->file, "r"))) {
            die(print("Couldn't open file: $this->file\n"));
        }
 
        while ($data = fread($fp, 4096)) {
          if (!xml_parse($xml_parser, $data, feof($fp))) {
            die(sprintf()("XML error: %s at line %d\n",
              xml_error_string(xml_get_error_code($xml_parser)),
              xml_get_current_line_number($xml_parser)));
          }
        }
    }
 
    function startElement($parser, $name, $attribs) {
        # Adding the additional element to the tree, including attributes
        $this->tree[] = $name;
 
        $node = new Node($this->tree);
        while (list($k, $v) = each($attribs)) {
            $node->attributes[$k] = $v;
      }
        $this->nodes[] = $node;
    }
 
    function endElement($parser, $name) {
        # Adding a new element, describing the end of the tag
        # But only, if the Tag has CDATA in it!
 
        # Check
        if (count($this->nodes) >= 1) {
            $prev_node = $this->nodes[count($this->nodes)-1];
            if (strlen($prev_node->data) > 0 || $prev_node->name != $name) {
                $this->tree[count($this->tree)-1] = "/".$this->tree[count($this->tree)-1];
                $this->nodes[] = new Node($this->tree, NULL);
            } else {
                # Adding a slash to the end of the prev_node
                $prev_node->name = $prev_node->name."/"
                $this->nodes[count($this->nodes)-1]->name = $this->nodes[count($this->nodes)-1]->name."/"
            }
        }
 
        # Removing the element from the tree
        array_pop($this->tree);
    }
 
    function characterData($parser, $data) {
        $data = ltrim($data);
        if ($data != "") $this->nodes[count($this->nodes)-1]->add_data($data);
    }
 
    function process_instruction($parser, $target, $data) {
        if (preg_match("/xml:stylesheet/", $target, $match) && preg_match("/type=\"text\/xsl\"/", $data, $match)) {
            preg_match("/href=/index.html"(.+)\"/i", $data, $this->PIs);
#            print "<b>found xls pi: $PIs[1]</b><br>\n"
        }
    }
 
    function print_nodes() {
        # Printing the header
        print "<html><head><title>".$this->nodes[0]->name."</title></head>"
        print "<body ".$this->format_body."\">\n"
 
        # Printing the XML  Data
        for ($i = 0; $i < count($this->nodes); $i++) {
            $node = $this->nodes[$i];
 
            # Checking: Empty element
            if ($node->name[strlen($node->name)-1] == "/") {
                $end_char = "/"
                $node->name = substr($node->name, 0, strlen($node->name)-1);
            } else {
                $end_char = ""
            }
 
            # Writing whitespaces, but only if it's _no_ closing element that follows
            # directly on it's opening element
            if (!("/".$this->nodes[$i-1]->name == $node->name)) {
                for ($j = 0; $j < $node->level(); $j++) echo $this->format_blanks;
            }
            echo "<span ".$this->format_bracket."\"><</span><span ".$this->format_element."\">".$node->name."</span>"
            if ($node->has_attributes()) {
                $keys = array_keys()($node->attributes);
                for ($j = 0; $j < count($keys); $j++) {
                    printf(" <span %s\">%s=\"</span><span %s\">%s</span><span %s\">\"</span>", $this->format_attribute_name, $keys[$j], $this->format_attribute_value, $node->attributes[$keys[$j]], $this->format_attribute_name);
                }
                echo " "
            }
 
            echo "<span ".$this->format_element."\">$end_char</span><span ".$this->format_bracket."\">></span>"
 
            if (strlen($node->data) > 0) echo "<span ".$this->format_data."\">".ltrim($node->data)."</span>"
            else echo "<br>\n"
        }
 
        # Printing the footer
        print "</body></html>\n"
    }
}

调用示例:
 

代码示例:
<?php
$xml = new XML('artikel.xml');
$xml->print_nodes();

    
[2]php打包一组文件为zip压缩包的类
    来源: 互联网  发布时间: 2013-12-24

php zip文件压缩类:
添加文件到数组,最后将添加的文件打包成zip。

代码:
 

代码示例:
<?php
/**
* Zip file creation class.
* Makes zip files.
*
* @access  public
*/
class zipfile
{
    /**
     * Array to store compressed data
     *
     * @public array    $datasec
     */
    public $datasec      = array();
 
    /**
     * Central directory
     *
     * @public array    $ctrl_dir
     */
    public $ctrl_dir     = array();
 
    /**
     * End of central directory record
     *
     * @public string   $eof_ctrl_dir
     */
    public $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
 
    /**
     * Last offset position
     *
     * @public integer  $old_offset
     */
    public $old_offset   = 0;
 
 
    /**
     * Converts an Unix timestamp to a four byte DOS date and time format (date
     * in high two bytes, time in low two bytes allowing magnitude comparison).
     *
     * @param  integer  the current Unix timestamp
     *
     * @return integer  the current date in a four byte DOS format
     *
     * @access private
     */
    function unix2DosTime($unixtime = 0) {
        $timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);
 
        if ($timearray['year'] < 1980) {
            $timearray['year']    = 1980;
            $timearray['mon']     = 1;
            $timearray['mday']    = 1;
            $timearray['hours']   = 0;
            $timearray['minutes'] = 0;
            $timearray['seconds'] = 0;
        } // end if
 
        return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) |
                ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
    } // end of the 'unix2DosTime()' method
 
 
    /**
     * Adds "file" to archive
     *
     * @param  string   file contents
     * @param  string   name of the file in the archive (may contains the path)
     * @param  integer  the current timestamp
     *
     * @access public
     */
    function addFile($data, $name, $time = 0)
    {
        $name     = str_replace()('\\', '/', $name);
 
        $dtime    = dechex($this->unix2DosTime($time));
        $hexdtime = '\x' . $dtime[6] . $dtime[7]
                  . '\x' . $dtime[4] . $dtime[5]
                  . '\x' . $dtime[2] . $dtime[3]
                  . '\x' . $dtime[0] . $dtime[1];
        eval('$hexdtime = "' . $hexdtime . '";');
 
        $fr   = "\x50\x4b\x03\x04";
        $fr   .= "\x14\x00";            // ver needed to extract
        $fr   .= "\x00\x00";            // gen purpose bit flag
        $fr   .= "\x08\x00";            // compression method
        $fr   .= $hexdtime;             // last mod time and date
 
        // "local file header" segment
        $unc_len = strlen($data);
        $crc     = crc32($data);
        $zdata   = gzcompress($data);
        $zdata   = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix crc bug
        $c_len   = strlen($zdata);
        $fr      .= pack('V', $crc);             // crc32
        $fr      .= pack('V', $c_len);           // compressed filesize
        $fr      .= pack('V', $unc_len);         // uncompressed filesize
        $fr      .= pack('v', strlen($name));    // length of filename
        $fr      .= pack('v', 0);                // extra field length
        $fr      .= $name;
 
        // "file data" segment
        $fr .= $zdata;
 
        // "data descriptor" segment (optional but necessary if archive is not
        // served as file)
        $fr .= pack('V', $crc);                 // crc32
        $fr .= pack('V', $c_len);               // compressed filesize
        $fr .= pack('V', $unc_len);             // uncompressed filesize
 
        // add this entry to array
        $this -> datasec[] = $fr;
 
        // now add to central directory record
        $cdrec = "\x50\x4b\x01\x02";
        $cdrec .= "\x00\x00";                // version made by
        $cdrec .= "\x14\x00";                // version needed to extract
        $cdrec .= "\x00\x00";                // gen purpose bit flag
        $cdrec .= "\x08\x00";                // compression method
        $cdrec .= $hexdtime;                 // last mod time & date
        $cdrec .= pack('V', $crc);           // crc32
        $cdrec .= pack('V', $c_len);         // compressed filesize
        $cdrec .= pack('V', $unc_len);       // uncompressed filesize
        $cdrec .= pack('v', strlen($name) ); // length of filename
        $cdrec .= pack('v', 0 );             // extra field length
        $cdrec .= pack('v', 0 );             // file comment length
        $cdrec .= pack('v', 0 );             // disk number start
        $cdrec .= pack('v', 0 );             // internal file attributes
        $cdrec .= pack('V', 32 );            // external file attributes - 'archive' bit set
 
        $cdrec .= pack('V', $this -> old_offset ); // relative offset of local header
        $this -> old_offset += strlen($fr);
 
        $cdrec .= $name;
 
        // optional extra field, file comment goes here
        // save to central directory
        $this -> ctrl_dir[] = $cdrec;
    } // end of the 'addFile()' method
 
 
    /**
     * Dumps out file
     *
     * @return  string  the zipped file
     *
     * @access public
     */
    function file()
    {
        $data    = implode('', $this -> datasec);
        $ctrldir = implode('', $this -> ctrl_dir);
 
        return
            $data .
            $ctrldir .
            $this -> eof_ctrl_dir .
            pack('v', sizeof($this -> ctrl_dir)) .  // total # of entries "on this disk"
            pack('v', sizeof($this -> ctrl_dir)) .  // total # of entries overall
            pack('V', strlen($ctrldir)) .           // size of central dir
            pack('V', strlen($data)) .              // offset to start of central dir
            "\x00\x00";                             // .zip file comment length
    } // end of the 'file()' method
 
 
    /**
     * A Wrapper of original addFile Function
     *
     * Created By Hasin Hayder at 29th Jan, 1:29 AM
     *
     * @param array An Array of files with relative/absolute path to be added in Zip File
     *
     * @access public
     */
    function addFiles($files /*Only Pass Array*/)
    {
        foreach($files as $file)
        {
        if (is_file($file)) //directory check
        {
            $data = implode("",file($file));
                    $this->addFile($data,$file);
                }
        }
    }
 
    /**
     * A Wrapper of original file Function
     *
     * Created By Hasin Hayder at 29th Jan, 1:29 AM
     *
     * @param string Output file name
     *
     * @access public
     */
    function output($file)
    {
        $fp=fopen($file,"w");
        fwrite($fp,$this->file());
        fclose($fp);
    } 
} // end of the 'zipfile' class

    
[3]php导出CSV文件的实现代码
    来源: 互联网  发布时间: 2013-12-24

php导出CSV文件,供Excel读取。
代码:
 

代码示例:
<?php
// 注意包含正确的类路径
require_once(dirname(__FILE__) . '/export.php');
$exceler= newJason_Excel_Export();
 
// 生成excel格式 这里根据后缀名不同而生成不同的格式。
$exceler->setFileName('jason_excel.xls');
 
// 生成csv格式
// $exceler->setFileName('jason_excel.csv');
 
// 设置excel标题行
$excel_title= array('第一列', '第二列', '第三列');
$exceler->setTitle($excel_title);
 
// 设置excel内容
$excel_data= array(
    array('1', '2', '3'), // 第一行
    array('1', '2', '3'), // 第二行
    array('1', '2', '3'), // 第三行
);
$exceler->setContent($excel_data);
 
// 生成excel
$exceler->export();
?>

    
最新技术文章:
▪PHP函数microtime()时间戳的定义与用法
▪PHP单一入口之apache配置内容
▪PHP数组排序方法总结(收藏)
▪php数组排序方法大全(脚本学堂整理奉献)
▪php数组排序的几个函数(附实例)
▪php二维数组排序(实例)
▪php根据键值对二维数组排序的小例子
▪php验证码(附截图)
▪php数组长度的获取方法(三个实例)
▪php获取数组长度的方法举例
▪判断php数组维度(php数组长度)的方法
▪php获取图片的exif信息的示例代码
▪PHP 数组key长度对性能的影响实例分析
▪php函数指定默认值的方法示例
▪php提交表单到当前页面、提交表单后页面重定...
▪php四舍五入的三种实现方法
▪php获得数组长度(元素个数)的方法
▪php日期函数的简单示例代码
▪php数学函数的简单示例代码
▪php字符串函数的简单示例代码
▪php文件下载代码(多浏览器兼容、支持中文文...
▪php实现文件下载、支持中文文件名的示例代码...
▪php文件下载(防止中文文件名乱码)的示例代码
▪解决PHP文件下载时中文文件名乱码的问题
▪php数组去重(一维、二维数组去重)的简单示例
▪php小数点后取两位的三种实现方法
▪php Redis 队列服务的简单示例
▪PHP导出excel时数字变为科学计数的解决方法
▪PHP数组根据值获取Key的简单示例
▪php数组去重的函数代码示例
 


站内导航:


特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

©2012-2021,,E-mail:www_#163.com(请将#改为@)

浙ICP备11055608号-3