在INI文件中使用关键字作为变量名

7

我有一个INI文件,其中包含以下内容:

[country]
SE = Sweden
NO = Norway
FI = Finland

然而,当我使用var_dump()函数输出PHP的parse_ini_file()函数时,我得到了以下输出:
PHP Warning:  syntax error, unexpected BOOL_FALSE in test.ini on line 2
in /Users/andrew/sandbox/test.php on line 1
bool(false)

看起来 "NO" 是被保留的。是否有其他方法可以设置一个名为 "NO" 的变量?

6个回答

4

另一种方法是将您的 ini 键与它们的值反转,然后使用 array_flip

<?php

$ini =
"
    [country]
    Sweden = 'SE'
    Norway = 'NO'
    Finland = 'FI'
";

$countries = parse_ini_string($ini, true);
$countries = array_flip($countries["country"]);
echo $countries["NO"];

如果您使用NO(至少)需要在其周围加上引号。

Norway = NO

您不会收到错误提示,但$countries["NO"]的值将为空字符串。

1
谢谢,那可能是唯一的方法。 - Andrew Danks
如果值不唯一,这会导致程序出错吧?毕竟它们只是,而不是键。 - Pacerier
我假设这是正确的,@Pacerier,因为我们正在谈论国家和它们的短代码。 - yannis

3
这可能有点晚了,但 PHP 的 parse_ini_file 函数让我很困扰,所以我写了自己的小解析器。您可以随意使用它,但请谨慎使用,因为它只经过了浅层测试!
// the exception used by the parser
class IniParserException extends \Exception {

    public function __construct($message, $code = 0, \Exception $previous = null) {
        parent::__construct($message, $code, $previous);
    }

    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }

}

// the parser
function my_parse_ini_file($filename, $processSections = false) {
    $initext = file_get_contents($filename);
    $ret = [];
    $section = null;
    $lineNum = 0;
    $lines = explode("\n", str_replace("\r\n", "\n", $initext));
    foreach($lines as $line) {
        ++$lineNum;

        $line = trim(preg_replace('/[;#].*/', '', $line));
        if(strlen($line) === 0) {
            continue;
        }

        if($processSections && $line{0} === '[' && $line{strlen($line)-1} === ']') {
            // section header
            $section = trim(substr($line, 1, -1));
        } else {
            $eqIndex = strpos($line, '=');
            if($eqIndex !== false) {
                $key = trim(substr($line, 0, $eqIndex));
                $matches = [];
                preg_match('/(?<name>\w+)(?<index>\[\w*\])?/', $key, $matches);
                if(!array_key_exists('name', $matches)) {
                    throw new IniParserException("Variable name must not be empty! In file \"$filename\" in line $lineNum.");
                }
                $keyName = $matches['name'];
                if(array_key_exists('index', $matches)) {
                    $isArray = true;
                    $arrayIndex = trim($matches['index']);
                    if(strlen($arrayIndex) == 0) {
                        $arrayIndex = null;
                    }
                } else {
                    $isArray = false;
                    $arrayIndex = null;
                }

                $value = trim(substr($line, $eqIndex+1));
                if($value{0} === '"' && $value{strlen($value)-1} === '"') {
                    // too lazy to check for multiple closing " let's assume it's fine
                    $value = str_replace('\\"', '"', substr($value, 1, -1));
                } else {
                    // special value
                    switch(strtolower($value)) {
                        case 'yes':
                        case 'true':
                        case 'on':
                            $value = true;
                            break;
                        case 'no':
                        case 'false':
                        case 'off':
                            $value = false;
                            break;
                        case 'null':
                        case 'none':
                            $value = null;
                            break;
                        default:
                            if(is_numeric($value)) {
                                $value = $value + 0; // make it an int/float
                            } else {
                                throw new IniParserException("\"$value\" is not a valid value! In file \"$filename\" in line $lineNum.");
                            }
                    }
                }

                if($section !== null) {
                    if($isArray) {
                        if(!array_key_exists($keyName, $ret[$section])) {
                            $ret[$section][$keyName] = [];
                        }
                        if($arrayIndex === null) {
                            $ret[$section][$keyName][] = $value;
                        } else {
                            $ret[$section][$keyName][$arrayIndex] = $value;
                        }
                    } else {
                        $ret[$section][$keyName] = $value;
                    }
                } else {
                    if($isArray) {
                        if(!array_key_exists($keyName, $ret)) {
                            $ret[$keyName] = [];
                        }
                        if($arrayIndex === null) {
                            $ret[$keyName][] = $value;
                        } else {
                            $ret[$keyName][$arrayIndex] = $value;
                        }
                    } else {
                        $ret[$keyName] = $value;
                    }
                }
            }
        }
    }

    return $ret;
}

它有何不同?变量名只能由字母和数字组成,但除此之外没有任何限制。字符串必须用“”括起来,其他所有内容都必须是特殊值,如noyestruefalseonoffnullnone。有关映射,请参见代码。


2

这有点像一种技巧,但你可以在键名周围添加反引号:

[country]
`SE` = Sweden
`NO` = Norway
`FI` = Finland

然后可以这样访问它们:
$result = parse_ini_file('test.ini');
echo "{$result['`NO`']}\n";

输出:

$ php test.php
Norway

1
这与仅将变量重命名为其他名称没有区别。使用您的解决方案,变量名称为 `NO`,而不是 NO。在配置文件中也可以这样做:πNOπ = Norway - Andrew Danks

0

我遇到了同样的问题,并尝试以各种方式转义名称。

然后我想起来,由于INI语法会修剪名称和值,因此以下解决方法或许可以解决问题:

NL = Netherlands
; A whitespace before the name
 NO = Norway
PL = Poland

它很有效 ;) 只要你的同事读了注释(这并不总是情况),并且不会意外删除它。因此,使用数组翻转解决方案是一个安全的选择。


0
当字符串中存在单引号组合(例如't或's)时,我遇到了这个错误。为了解决这个问题,我将字符串用双引号括起来:

之前:

You have selected 'Yes' but you haven't entered the date's flexibility

之后:

"You have selected 'Yes' but you haven't entered the date's flexibility"

-1

来自parse_ini_file的手册页面:

有一些保留字不能用作ini文件的键。这些包括:null、yes、no、true、false、on、off、none。

所以,不,你不能设置一个名为NO的变量。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接