有一种简单的方法可以在PHP中以数组格式读取文件内容吗?

时间:2013-08-22 01:54:25

标签: php string file

我正在尝试使用文件(.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()函数,但它并没有真正实现我想要的东西,或者我可能会遗漏一些东西。

4 个答案:

答案 0 :(得分:2)

我为你写了一个快速的脚本, 我假设你的(文件).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);

答案 1 :(得分:0)

您可以使用file_get_contents

阅读

例如:

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

希望它会有所帮助:)

答案 2 :(得分:0)

我想@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];
  }

答案 3 :(得分:0)

Matt在PHP手册中分享了一个名为print_r_reverse的功能,我认为这就是你想要的。以下代码直接从PHP手册print_r函数注释部分复制。

<?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; 
    } 
}