使用php怎么实现tab分割文件

发布时间:2021-02-03 11:00:31 作者:Leah
来源:亿速云 阅读:190

使用php怎么实现tab分割文件?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

//
// save an array as tab seperated text file
//
function write_tabbed_file($filepath, $array, $save_keys=false){
  $content = '';
  reset($array);
  while(list($key, $val) = each($array)){
    // replace tabs in keys and values to [space]
    $key = str_replace("\t", " ", $key);
    $val = str_replace("\t", " ", $val);
    if ($save_keys){ $content .= $key."\t"; }
    // create line:
    $content .= (is_array($val)) ? implode("\t", $val) : $val;
    $content .= "\n";
  }
  if (file_exists($filepath) && !is_writeable($filepath)){ 
    return false;
  }
  if ($fp = fopen($filepath, 'w+')){
    fwrite($fp, $content);
    fclose($fp);
  }
  else { return false; }
  return true;
}
//
// load a tab seperated text file as array
//
function load_tabbed_file($filepath, $load_keys=false){
  $array = array();
  if (!file_exists($filepath)){ return $array; }
  $content = file($filepath);
  for ($x=0; $x < count($content); $x++){
    if (trim($content[$x]) != ''){
      $line = explode("\t", trim($content[$x]));
      if ($load_keys){
        $key = array_shift($line);
        $array[$key] = $line;
      }
      else { $array[] = $line; }
    }
  }
  return $array;
}
/*
** Example usage:
*/
$array = array(
  'line1' => array('data-1-1', 'data-1-2', 'data-1-3'),
  'line2' => array('data-2-1', 'data-2-2', 'data-2-3'),
  'line3' => array('data-3-1', 'data-3-2', 'data-3-3'),
  'line4' => 'foobar',
  'line5' => 'hello world'
);
// save the array to the data.txt file:
write_tabbed_file('data.txt', $array, true);
/* the data.txt content looks like this:
line1 data-1-1 data-1-2 data-1-3
line2 data-2-1 data-2-2 data-2-3
line3 data-3-1 data-3-2 data-3-3
line4 foobar
line5 hello world
*/
// load the saved array:
$reloaded_array = load_tabbed_file('data.txt',true);
print_r($reloaded_array);
// returns the array from above

关于使用php怎么实现tab分割文件问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. tab.py 文件
  2. python如何实现文件的分割与合并

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php

上一篇:MySQL中删除表操作实现有哪些区别

下一篇:如何在php项目中实现一个单态设计模式

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》