将字符串格式化为csv数据

fputcsv() 函数用于将数据格式为csv格式,以便写入文件或者数据库。

1.将字符串写入csv文件中

 
  
$test_array = array (
array ( " 111 " , " sdfsd " , " sdds " , " 43344 " , " rrrr " ) ,
array ( " sssssssss " , " gdfgfd " , " 232323 " , " wwewe " , " dsfds " ) ,
array ( " fgfg " , " e4343 " , " dsfds " , " w2332 " , " xcvxc " ) ,
array ( " 11212 " , " 2323 " , " 344343 " , " 344343 " , " rerreer " ) ,
array ( " fds " , " 43344444 " , " 33333333 " , " ttttttt " , " gggggggggggg " ) ,
array ( " kdfs " , " dsfdsfds " , " wewewe " , " sdsdddddddd " , " wwwwwwwwwww " )
);

$file = fopen ( " test.csv " , " w " ) or die ( " Can't Open test.csv " );
foreach ( $test_array as $line_array )
{
$isSuccess = fputcsv( $file , $line_array );
print $isSuccess."<br>";
     if ( $isSuccess === false )
{
die ( " Can't write csv line " . $line_array );
}
}
fclose ( $file ) or die ( " Can't close file test.csv. " );

fputcsv()函数返回所写入行的字符的个数或者false,当写入失败时返回false。

2.将格式化的csv字符串保存到字符串中。

 
  
$test_array = array (
array ( " 111 " , " sdfsd " , " sdds " , " 43344 " , " rrrr " ) ,
array ( " sssssssss " , " gdfgfd " , " 232323 " , " wwewe " , " dsfds " ) ,
array ( " fgfg " , " e4343 " , " dsfds " , " w2332 " , " xcvxc " ) ,
array ( " 11212 " , " 2323 " , " 344343 " , " 344343 " , " rerreer " ) ,
array ( " fds " , " 43344444 " , " 33333333 " , " ttttttt " , " gggggggggggg " ) ,
array ( " kdfs " , " dsfdsfds " , " wewewe " , " sdsdddddddd " , " wwwwwwwwwww " )
);
ob_start ();
$file = fopen ( " php://output " , " w " ) or die ( " Can't Open php://output " );
foreach ( $test_array as $line_array )
{
$isSuccess = fputcsv( $file , $line_array );
if ( $isSuccess === false )
{
die ( " Can't write csv line " . $line_array );
}
}

fclose ( $file ) or die ( " Can't close file test.csv. " );
$result = ob_get_contents ();
ob_end_clean ();

转载于:https://www.cnblogs.com/ywxgod/archive/2011/05/25/2057383.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值