将文件解析为数组时的额外空白值

时间:2018-01-20 21:44:11

标签: php text-parsing

编辑:检查!空工作 - 但我仍然想知道为什么在文件结束后似乎还在继续。谢谢!

我正在尝试解析一个看起来像这样的文件:

export NTPSERVER_1 NTPSERVER_2 NTPSERVER_3 PSLOGHOST LOGHOST RSSHHOST RHPORT
NTPSERVER_1=8.8.8.8
NTPSERVER_2=
NTPSERVER_3=
LOGHOST="8.8.8.8"
PSLOGHOST=""
RSSHHOST="8.8.8.8"
RHPORT=88888

它工作得很好,除了数组中有一个额外的最后一个值,没有键和空值。我试过添加一个检查$ line为null无效。我已经仔细检查过该文件在RHPORT行之后没有任何空行。 我得到了一个"注意:未定义的偏移量:1"消息和数组中的最后一件事是[""] =>空值 我不明白为什么这段时间似乎没有停在文件的末尾。

$file = fopen("files/network.conf","r");
$i = 0;

while(! feof($file)) {

  $line = fgets($file);

  if ($i > 0 && !is_null($line)) { // skipping first line of file

    $array = explode('=',$line);
    $fileValues[$array[0]] = $array[1];

  }
  $i++;
}
fclose($file);

2 个答案:

答案 0 :(得分:2)

我建议您使用file()功能

$array = file('file path', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$final_array = [];//empty array declaration
foreach($array as $arr){ // iterate over array get from file() function
   $exploded_array = explode('=',$arr);
   $final_array[$exploded_array[0]] = $exploded_array[1];
}
print_r($final_array);

正如您所看到的只需要一行代码,您将得到所需的数组

答案 1 :(得分:0)

您可以使用file_get_contents和regex来获取值。

// Uncomment line below
//$str =file_get_contents("files/network.conf");
$str = 'export NTPSERVER_1 NTPSERVER_2 NTPSERVER_3 PSLOGHOST LOGHOST RSSHHOST RHPORT
NTPSERVER_1=8.8.8.8
NTPSERVER_2=
NTPSERVER_3=
LOGHOST="8.8.8.8"
PSLOGHOST=""
RSSHHOST="8.8.8.8"
RHPORT=88888';

// Find lines with = and save them to $matches[1] and [2]
Preg_match_all("/(\w+)\=(.*)/", $str, $matches);

// Create array as you expect
Foreach($matches[1] as $key => $val){
    $res[$val] = str_replace('"','',$matches[2][$key]); // remove " if it exists.
}

Var_dump($res);

https://3v4l.org/CO59t

相关问题