找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 654|回复: 0
打印 上一主题 下一主题

php将文本文件转换csv输出的方法

[复制链接]

2536

主题

2536

帖子

7532

积分

论坛元老

Rank: 8Rank: 8

积分
7532
跳转到指定楼层
楼主
发表于 2018-2-14 05:50:45 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

            本文实例讲述了php将文本文件转换csv输出的方法。分享给大家供大家参考。具体实现方法如下:
这个类提供了转换成固定宽度的CSV文件,快速,简便的方法,它可将SplFileObject用于执行迭代,使它非常高效的一个迭代只知道当前成员,期权是提供给指定行字符和字段分隔符结束,This from CSV files.这个类是特别有用的,如果数据需要来自一个固定宽度的文件,并插入到数据库中,因为大多数的数据库支持从CSV文件中的数据输入.
这一类的方便的功能是可以跳过字段如果不是在输出需要,该领域的阵列提供,提供了一个键/值对,与主要持有的价值偏移,或启动领域的地位,和值包含的宽度,或字段的长度,For example.例如,12 =“10是一个领域,在12位和宽度或字段的长度为10个字符开始.
底的行字符默认成“ n”,而是可以设置为任何字符。
分隔符默认为一个逗号,但可以设置为任何字符,或字符。
从文件的输出可以直接使用,写入一个文件,到数据库或任何其他目的插入.
PHP实例代码如下:
[U]复制代码[/U] 代码如下: $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示例用法
[U]复制代码[/U] 代码如下: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 ();  
}
?>
希望本文所述对大家的php程序设计有所帮助。
            
            
您可能感兴趣的文章:
  • 自动把纯文本转换成Web页面的php代码
  • php中将html中的br换行符转换为文本输入中的换行符
  • php导出csv格式数据并将数字转换成文本的思路以及代码分享
  • 把文本中的URL地址转换为可点击链接的JavaScript、PHP自定义函数
  • PHP实现把文本中的URL转换为链接的auolink()函数分享
  • php实现使用正则将文本中的网址转换成链接标签
  • PHP将HTML转换成文本的实现代码
  • php实现二进制和文本相互转换的方法
  • 分享php代码将360浏览器导出的favdb的sqlite数据库文件转换为html
  • 使用PHP+JavaScript将HTML页面转换为图片的实例分享
  • php实现转换html格式为文本格式的方法
            
  • 分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    用户反馈
    客户端