EDIT: checking for !empty works - but I would still like to know why the while seems to be continuing on after the end of the file. Thanks!
I am trying to parse a file that looks like:
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
It's working great, except there is an extra last value in the array with no key and a null value. I have tried adding a check for $line being null to no avail. And I have double checked that the file does not have any blank lines after the RHPORT line. I am getting a "Notice: Undefined offset: 1" message and last thing in the array is [""]=> NULL I don't understand why the while doesn't seem to be stopping at the end of the file.
$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);
I will recommend you to use file() function
$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);
As you can see only one-line code needed and you will get desired array