您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

php 将文本文件转换csv输出

2025/12/8 0:44:01发布24次查看
这个类提供了转换成固定宽度的csv文件,快速,简便的方法,它可将splfileobject用于执行迭代,使它非常高效的一个迭代只知道当前成员,期权是提供给指定行字符和字段分隔符结束,this from csv files.这个类是特别有用的,如果数据需要来自一个固定宽度的文件,并插入到数据库中,因为大多数的数据库支持从csv文件中的数据输入.
这一类的方便的功能是可以跳过字段如果不是在输出需要,该领域的阵列提供,提供了一个键/值对,与主要持有的价值偏移,或启动领域的地位,和值包含的宽度,或字段的长度,for example.例如,12 =“10是一个领域,在12位和宽度或字段的长度为10个字符开始.
底的行字符默认成 n,而是可以设置为任何字符。
分隔符默认为一个逗号,但可以设置为任何字符,或字符。
.从文件的输出可以直接使用,写入一个文件,到数据库或任何其他目的插入.
php实例代码如下:
$name = $value; break; default: throw new exception(unable to set $name ); } } /** * * gettor this is called when trying to access a non-existing property * * @access public * @param string $name the name of the property * @throw exception if proplerty cannot be set * @return string * */ public function __get($name) { switch ($name) { case 'eol': return ; case 'fields': return array(); case 'separator': return ','; default: throw new exception( $name cannot be set); } } /** * * over ride the parent current method and convert the lines * * @access public * @return string the line as a csv representation of the fixed width line, false otherwise * */ public function current() { if (parent::current()) { $csv = ''; $fields = new cachingiterator(new arrayiterator($this->fields)); foreach ($fields as $f) { $csv.= trim(substr(parent::current() , $fields->key() , $fields->current())); $csv.= $fields->hasnext() ? $this->separator : $this->eol; } return $csv; } return false; }} // end of class?> example usage示例用法 width of each field ***/ $file->fields = array( 0 => 10, 10 => 15, 25 => 20, 45 => 25 ); /*** output the converted lines ***/ foreach ($file as $line) { echo $line; } /*** a new instance ***/ $new = new fixed2csv('my_file.txt'); /*** get only first and third fields ***/ $new->fields = array( 0 => 10, 25 => 20 ); /*** output only the first and third fields ***/ foreach ($new as $line) { echo $line; }}catch(exception $e) { echo $e->getmessage();}?>
教程地址:
欢迎转载!但请带上文章地址^^
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product