【问题标题】:Reading INI file from PHP which contains Semicolons从 PHP 中读取包含分号的 INI 文件
【发布时间】:2015-01-07 11:00:37
【问题描述】:

我必须阅读 PHP 中包含分号条目的配置文件,例如

[section]
key=value;othervalue

我注意到parse_ini_file() 删除了所有分号以及后面的内容,即使设置为INI_SCANNER_RAW

INI 文件来自旧系统,我无法更改格式。我只需要阅读它们。

当我必须用分号保留条目时,最好使用什么工具?

【问题讨论】:

  • 引用 ini 文件中的条目:key="value;othervalue"... 否则 ; 引入注释
  • 很遗憾,我无法更改 INI 文件。它们来自一个只有行首的分号表示注释的环境。该环境中的许多有效 etries 在值中包含分号。
  • @MarkBaker 那条评论应该是公认的答案????

标签: php parsing ini


【解决方案1】:

我建议先将文件读入一个数组,将分号转换为管道 |,然后将其吐出到一个临时文件中,然后对新的临时文件使用 parse_ini_file()。

就这样……

$string = file_get_contents('your_file');

$newstring = str_replace(";","|",$string);

$tempfile = 'your_temp_filename';

file_put_contents($tempfile, $newstring);

$arrIni = parse_ini_file($tempfile);

然后,在枚举新的基于 INI 的数组时,您总是可以用分号替换管道。

【讨论】:

    【解决方案2】:

    对于 ini 文件,; 是注释符号。 所以实际上最好不要将其用于其他用途。

    但是,您可以使用 here 找到的解决方案中的这个稍作修改的函数:

    <?php
    //Credits to goulven.ch AT gmail DOT com 
    function parse_ini ( $filepath )
    {
        $ini = file( $filepath );
        if ( count( $ini ) == 0 ) { return array(); }
        $sections = array();
        $values = array();
        $globals = array();
    
        $i = 0;
        foreach( $ini as $line ){
            $line = trim( $line );
            // Comments
            if ( $line == '' || $line{0} == ';' ) { continue; }
            // Sections
            if ( $line{0} == '[' )
            {
                $sections[] = substr( $line, 1, -1 );
                $i++;
                continue;
            }
            // Key-value pair
            list( $key, $value ) = explode( '=', $line, 2 );        
            $key = trim( $key );
            $value = trim( $value );
    
            if (strpos($value, ";") !== false)
                $value = explode(";", $value);
    
            if ( $i == 0 ) {
                // Array values
                if ( substr( $line, -1, 2 ) == '[]' ) {
                    $globals[ $key ][] = $value;
                } else {
                    $globals[ $key ] = $value;
                }
            } else {
                // Array values
                if ( substr( $line, -1, 2 ) == '[]' ) {
                    $values[ $i - 1 ][ $key ][] = $value;
                } else {
                    $values[ $i - 1 ][ $key ] = $value;
                }
            }
        }
        for( $j=0; $j<$i; $j++ ) {
            $result[ $sections[ $j ] ] = $values[ $j ];
        }
        return $result + $globals;
    }
    

    您可以在链接后查看使用示例。

    【讨论】:

      猜你喜欢
      • 2016-01-09
      • 1970-01-01
      • 2012-10-15
      • 2017-11-16
      • 2012-06-29
      • 1970-01-01
      • 1970-01-01
      • 2014-02-20
      • 2023-02-21
      相关资源
      最近更新 更多