【问题标题】:Is there an easy way to read file contents in array format in PHP?有没有一种简单的方法可以在 PHP 中以数组格式读取文件内容?
【发布时间】:2013-08-24 14:15:54
【问题描述】:

我正在尝试使用文件(.txt)来打印日志。在文件中,它记录了一个如下所示的数组值:

  Array
  (
      [NAME] => John Peters
      [AGE] => 24
      [COUNTRY] => United States
      [EMAIL] => test@test.com
  )

所以现在,我正在尝试读取文件内容并将其转换为实际数组,以便能够使用 php 文件中的数组键引用该值,例如:

  echo 'Name : ' .$person['NAME'];
  echo 'Age: ' .$person['AGE'];
  echo 'Country: ' .$person['COUNTRY'];
  echo 'Email: ' .$person['EMAIL'];

是否有预定义的 php 函数来执行此操作?或者我将如何能够完成我想要的。我尝试使用 fread() 和 fgets() 函数,但它并没有真正完成我想要的,或者我可能会遗漏一些东西。

【问题讨论】:

  • 你为什么要这样记录呢?只需记录 JSON,然后将文件解析为 JSON。轻松愉快。
  • 你试过file_get_contents( ) 吗?另请参阅 SO => stackoverflow.com/questions/9529112/… 上的此问答
  • 您也可以在将数据存储到日志文件之前对数据使用serialize(),然后在加载时使用unserialize()

标签: php string file


【解决方案1】:

我为你写了一个快速脚本, 我假设在您的 (files).txt 中可以包含许多 print_r 结果条目,例如

Array
  (
      [NAME] => John Peters
      [AGE] => 24
      [COUNTRY] => United States
      [EMAIL] => test@test.com
  )
Array
  (
      [NAME] => John Peters
      [AGE] => 24
      [COUNTRY] => United States
      [EMAIL] => test@test.com
  )

此脚本假定您的输入 test.txt 仅包含具有 1 级的数组(因此,它不适用于嵌套数组)

$c = file_get_contents('test.txt');

# Matches all strings that has 'Array(...)' pattern
preg_match_all('#Array[^\)]+\)#', $c, $matches);

$items = array();
foreach($matches[0] as $match) {

    # Extracts KEY => VAL patterns from matched text 
    if (preg_match_all('#\[([^\]]+)\].*?>(.*)#', $match, $array)) {
        $items[] = array_combine($array[1], $array[2]);
    }
}

# test your results
print_r($items);

【讨论】:

    【解决方案2】:

    您可以使用file_get_contents阅读它

    例如:

    <?php
    $homepage = file_get_contents('abc.txt');
    echo $homepage;
    ?>
    

    希望它会有所帮助:)

    【讨论】:

    • 问题是没有读入文件的实际内容,而是将数据转换为合适的值,在这种情况下将其转换为数组。
    【解决方案3】:

    我猜@Rezigned 和我有同样的想法......这是我想出的:

    <?php
      $file = file_get_contents('log.txt');
      $file = preg_match_all('/(\s+\[[a-zA-Z0-9]+\]\s+=>\s+.+)\n/', $file, $lines);
      $key = array();
      $val = array();
      foreach ($lines[0] as $line) {
        $keys_vals = preg_split('/(\s+=>\s+)/', $line);
        $key[] .= preg_replace('/[\[|\]]/', '', $keys_vals[0]);
        $val[] .= $keys_vals[1];
      }
      $line_count = count($lines[0]);
      for ($i = 0; $i < $line_count; $i++) {
        print $key[$i] . ': ' . $val[$i];
      }
    

    【讨论】:

      【解决方案4】:

      在 PHP 手册中有一个 Matt 共享的函数,叫做print_r_reverse,我想这就是你想要的。以下代码直接复制自PHP手册print_r函数cmets部分。

      <?php 
      function print_r_reverse($in) { 
          $lines = explode("\n", trim($in)); 
          if (trim($lines[0]) != 'Array') { 
              // bottomed out to something that isn't an array 
              return $in; 
          } else { 
              // this is an array, lets parse it 
              if (preg_match("/(\s{5,})\(/", $lines[1], $match)) { 
                  // this is a tested array/recursive call to this function 
                  // take a set of spaces off the beginning 
                  $spaces = $match[1]; 
                  $spaces_length = strlen($spaces); 
                  $lines_total = count($lines); 
                  for ($i = 0; $i < $lines_total; $i++) { 
                      if (substr($lines[$i], 0, $spaces_length) == $spaces) { 
                          $lines[$i] = substr($lines[$i], $spaces_length); 
                      } 
                  } 
              } 
              array_shift($lines); // Array 
              array_shift($lines); // ( 
              array_pop($lines); // ) 
              $in = implode("\n", $lines); 
              // make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one) 
              preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER); 
              $pos = array(); 
              $previous_key = ''; 
              $in_length = strlen($in); 
              // store the following in $pos: 
              // array with key = key of the parsed array's item 
              // value = array(start position in $in, $end position in $in) 
              foreach ($matches as $match) { 
                  $key = $match[1][0]; 
                  $start = $match[0][1] + strlen($match[0][0]); 
                  $pos[$key] = array($start, $in_length); 
                  if ($previous_key != '') $pos[$previous_key][1] = $match[0][1] - 1; 
                  $previous_key = $key; 
              } 
              $ret = array(); 
              foreach ($pos as $key => $where) { 
                  // recursively see if the parsed out value is an array too 
                  $ret[$key] = print_r_reverse(substr($in, $where[0], $where[1] - $where[0])); 
              } 
              return $ret; 
          } 
      } 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-31
        • 2011-03-07
        • 2013-03-08
        • 2011-03-02
        • 1970-01-01
        • 2011-11-03
        • 1970-01-01
        • 2018-11-17
        相关资源
        最近更新 更多