php实现读取和写入tab分割的文件

yipeiwu_com6年前PHP代码库

本文实例讲述了php实现读取和写入tab分割的文件。分享给大家供大家参考。具体分析如下:

这段php代码实现读取和写入tab分割的文件,包含两个独立的函数,一个读,一个写,例如cvs文件等

//
// 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程序设计有所帮助。

相关文章

php中简单的对称加密算法实现

前言 在网上找到了一个不错的PHP方面的对称加密算法;在PHP的语法环境里,有urlencode与urldecode,base64_encode和base64_decode自带的对称算法...

php传值赋值和传地址赋值用法实例分析

本文实例讲述了php传值赋值和传地址赋值用法。分享给大家供大家参考。具体如下: <?php $name = 'Simon'; //对变量$name进行赋值(传值赋值)...

php 生成唯一id的几种解决方法

网上查了下,有很多的方法 1、md5(time() . mt_rand(1,1000000));   这种方法有一定的概率会出现重复 2、php内置函数uniqid()   uniqid...

file_get_contents(&quot;php://input&quot;, &quot;r&quot;)实例介绍

file_get_contents(&quot;php://input&quot;, &quot;r&quot;)实例介绍

解释不清,直接上例子index.html复制代码 代码如下:  <form action="action.php" method="post" >  &l...

PHP对象相关知识总结

对象传递:一种说法是“PHP对象是通过引用传递的”,更准确的说法是别名(标识符)传递,即它们都保存着同一个标识符(ID)的拷贝,这个标识符指向同一个对象的真正内容。 <...