配置文件到数组后的PHP未定义索引

时间:2013-03-28 10:36:14

标签: php arrays file undefined-index

这是我的配置加载代码:

    $WConfig;
    $lines = file($ToRootDirectory . 'config.txt', FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line_num => $line) {
        $line = trim($line);
        if (!(substr($line, 0, 1) == '#')){
            $WConfig[(trim(substr($line, 0, strpos($line, ":"))))] = trim(substr($line, strpos($line, ':') + 1));
        }
    }
    unset($lines, $line, $line_num, $temp);
    $host = $WConfig['mshost']; //line 11
    print_r($WConfig);          //line 12

加载此配置文件:(ANSI)

    #--/ MySQL:             //Dont forget to execute Install.sql ;)
    #      username:        //NOT NEEDED TO BE ROOT -> Acces to INSERT, UPDATE, SELECT, SHOW
    msusername:PHP_Default
    #      password:
    mspassword:php
    #      database:
    msdatabase:PHP_Default
    #      host:
    mshost:localhost
    #--/ Session:
    #       sessionend: Time in minutes when the session will be end from last acces. Default 20 minutes.

SESSIONEND:20

但显示:

Notice: Undefined index: mshost in C:\######\PHP\LoadConfig.php on line 11
Array ( [msusername] => PHP_Default [mspassword] => php [msdatabase] => PHP_Default [mshost] => localhost [sessionend] => 20 ) 

第11行出错,因为他找不到'mshost',但如果我在第12行显示数组,'mshost'仍然存在。

谁知道这个问题的答案,我需要做些什么才能解决这个问题?

更新:它仅由msusername和mshost

显示

答案:我已将msusername和mshost更改为数字 - > 0和1.这很好。

1 个答案:

答案 0 :(得分:0)

您的配置文件看起来很像INI。 (实际上,与INI完全相同,除了:而不是=)

我建议您使用PHP's INI loading routines来避免此类问题。

您的文件采用INI格式,如下所示:

; Use sections if you want
[MySQL]
;--/ MySQL:             //Dont forget to execute Install.sql ;)
;      username:        //NOT NEEDED TO BE ROOT -> Acces to INSERT, UPDATE, SELECT, SHOW
msusername = PHP_Default

;      password:
mspassword = php

;      database:
msdatabase = PHP_Default

;      host:
mshost = localhost

[Sessions]
;--/ Session:
;       sessionend: Time in minutes when the session will be end from last acces. Default 20 minutes.