php将文本文件转换csv输出的方法
本文实例讲述了php将文本文件转换csv输出的方法。分享给大家供大家参考。具体实现方法如下:
这个类提供了转换成固定宽度的CSV文件,快速,简便的方法,它可将SplFileObject用于执行迭代,使它非常高效的一个迭代只知道当前成员,期权是提供给指定行字符和字段分隔符结束,ThisfromCSVfiles.这个类是特别有用的,如果数据需要来自一个固定宽度的文件,并插入到数据库中,因为大多数的数据库支持从CSV文件中的数据输入.
这一类的方便的功能是可以跳过字段如果不是在输出需要,该领域的阵列提供,提供了一个键/值对,与主要持有的价值偏移,或启动领域的地位,和值包含的宽度,或字段的长度,Forexample.例如,12=“10是一个领域,在12位和宽度或字段的长度为10个字符开始.
底的行字符默认成“n”,而是可以设置为任何字符。
分隔符默认为一个逗号,但可以设置为任何字符,或字符。
从文件的输出可以直接使用,写入一个文件,到数据库或任何其他目的插入.
PHP实例代码如下:
<?php /** *ClasstoconvertfixedwidthfilesintoCSVformat *Allowstosetfields,separator,andend-of-linecharacter * *@authorKevinWaterson *@urlhttp://phpro.org *@version$Id$ * */ classfixed2CSVextendsSplFileObject { /** * *Constructor,duh,callstheparentconstructor * *@access public *@param string Thefullpathtothefiletobeconverted * */ publicfunction__construct($filename) { parent::__construct($filename); } /* *Settor,iscalledwhentryingtoassignavaluetonon-existingproperty * *@access public *@param string $name Thenameofthepropertytoset *@param mixed $value Thevalueoftheproperty *@throw Excptionifpropertyisnotabletobeset * */ publicfunction__set($name,$value) { switch($name) { case'eol': case'fields': case'separator': $this->$name=$value; break; default: thrownewException("Unabletoset$name"); } } /** * *GettorThisiscalledwhentryingtoaccessanon-existingproperty * *@access public *@param string $name Thenameoftheproperty *@throw Exceptionifproplertycannotbeset *@return string * */ publicfunction__get($name) { switch($name) { case'eol': return""; case'fields': returnarray(); case'separator': return','; default: thrownewException("$namecannotbeset"); } } /** * *Overridetheparentcurrentmethodandconvertthelines * *@access public *@return string ThelineasaCSVrepresentationofthefixedwidthline,falseotherwise * */ publicfunctioncurrent() { if(parent::current()) { $csv=''; $fields=newcachingIterator(newArrayIterator($this->fields)); foreach($fieldsas$f) { $csv.=trim(substr(parent::current(),$fields->key(),$fields->current() )); $csv.=$fields->hasNext()?$this->separator:$this->eol; } return$csv; } returnfalse; } }//endofclass ?>
ExampleUsage示例用法
<?php try { /***thefixedwidthfiletoconvert***/ $file=newfixed2CSV('my_file.txt'); /***Thestartposition=>widthofeachfield***/ $file->fields=array(0=>10,10=>15,25=>20,45=>25); /***outputtheconvertedlines***/ foreach($fileas$line) { echo$line; } /***anewinstance***/ $new=newfixed2CSV('my_file.txt'); /***getonlyfirstandthirdfields***/ $new->fields=array(0=>10,25=>20); /***outputonlythefirstandthirdfields***/ foreach($newas$line) { echo$line; } } catch(Exception$e) { echo$e->getMessage(); } ?>
希望本文所述对大家的php程序设计有所帮助。