简体   繁体   English

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

[英]Is there an easy way to read file contents in array format in PHP?

I am trying to make use of files(.txt) to print logs. 我正在尝试使用文件(.txt)来打印日志。 Inside the file, it logs an array value which looks like this: 在文件内部,它记录一个如下所示的数组值:

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

So now, I am trying to read the file contents and covert it onto an actual array so that I would be able to reference the value using the array key in a php file, something like: 所以现在,我正在尝试读取文件内容并将其转换为实际数组,以便我能够使用php文件中的数组键引用该值,例如:

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

Is there a predefined php function to do it? 是否有预定义的PHP函数来做到这一点? Or how will I be able to accomplish what I want. 或者我将如何实现我想要的目标。 I have tried to use the fread() and fgets() function but it doesn't really accomplish what I want or I might be missing something. 我曾尝试使用fread()和fgets()函数,但它并没有真正实现我想要的东西,或者我可能会遗漏一些东西。

I wrote a quick script for you, I assumed that in your (files).txt can contain many entries of print_r results eg 我为你写了一个快速脚本,我假设你的(文件).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
  )

This script assumes that your inputs test.txt only contains array that has 1 level (so, it won't work with nested array) 此脚本假定您的输入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);

you can read it using file_get_contents 你可以使用file_get_contents来阅读它

Eg: 例如:

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

Hope it will help :) 希望它会有所帮助:)

I guess @Rezigned and I had the same idea... Here's what I came up with: 我想@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];
  }

There is a function shared by Matt in PHP manual called print_r_reverse , I think it's what you want. Matt在PHP手册中分享了一个名为print_r_reverse ,我认为这就是你想要的。 The following code is copied from PHP manual print_r function comments section directly. 以下代码直接从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; 
    } 
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM