【问题标题】:Extra blank value when parsing file to array将文件解析为数组时的额外空白值
【发布时间】:2018-01-20 21:44:10
【问题描述】:

编辑: 检查 !empty 是否有效 - 但我仍然想知道为什么文件结束后 while 似乎仍在继续。谢谢!

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

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”消息,数组中的最后一件事是 [""]=> NULL 我不明白为什么 while 似乎没有在文件末尾停止。

$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);

【问题讨论】:

    标签: php text-parsing


    【解决方案1】:

    我会推荐你​​使用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);
    

    你可以看到只需要一行代码,你会得到想要的数组

    【讨论】:

    • 谢谢,这是一个有用的函数,但这不是我想要的数组
    • @SeeSamRun 您现在可以轻松地将此数组操作为您想要的数组。请检查我编辑的解决方案。我做到了
    • @SeeSamRun 很高兴为您提供帮助:):)
    【解决方案2】:

    您可以使用 file_get_contents 和正则表达式来获取值。

    // 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

    【讨论】:

      猜你喜欢
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      • 2014-11-23
      • 1970-01-01
      • 1970-01-01
      • 2013-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多