Gene Vincent
Gene Vincent

Reputation: 5469

Reading INI file from PHP which contains Semicolons

I have to read config files in PHP which contain entries with semicolons, e.g.

[section]
key=value;othervalue

I notices that parse_ini_file() removes all semicolons and what follows, even when set to INI_SCANNER_RAW.

The INI files come from legacy systems and I can't change the format. I only have to read them.

What's the best tool to use when I have to preserve the entries with semicolons?

Upvotes: 0

Views: 1267

Answers (2)

DarkaMaul
DarkaMaul

Reputation: 41

For ini files, the ; is the comment symbol. So it's actually a good idea to not use it for something else.

However, you can use this slightly modified functions from the solutions found 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;
}

You can see examples of usage following the link.

Upvotes: 1

Jason Howell
Jason Howell

Reputation: 118

I would recommend reading the file into an array first, convert the semicolons to pipes |, then spit that out to a temporary file and use parse_ini_file() with that new temporary file.

Like so...

$string = file_get_contents('your_file');

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

$tempfile = 'your_temp_filename';

file_put_contents($tempfile, $newstring);

$arrIni = parse_ini_file($tempfile);

Then after that you could always replace the pipes with semicolons as you enumerate your new INI based array.

Upvotes: 4

Related Questions