update page now

Voting

: eight minus three?
(Example: nine)

The Note You're Voting On

anatilmizun at gmail dot com
21 years ago
I wrote a pair of functions using parse_str() that will write values in an array to a textfile and vice versa, read those values from the textfile back into the array. Quite useful if you need to store lots of data but don't have access to SQL.

Save the array by calling cfg_save($filename,$array) and load it back using $array=cfg_load($filename)

<?php
$newline="?";

function cfg_load($cfgfile){
    global $newline;
    $setting="";
    if(file_exists($cfgfile)){
        $setting=fopen($cfgfile, "r");
        $ookk="";
        while($ook=fgets($setting)){
            #strip comment
            $commt=strpos($ook,"##");
            if($commt!==false) $ook=substr($ook,0,$commt);
            #append
            if($ook!="") $ookk=$ookk."&".    str_replace($newline,"\n",str_replace("&","%26",trim($ook)));
        }    
        fclose($setting);    
        parse_str($ookk, $setting);
    }
    return $setting;
}

function cfg_save($cfgfile,$setting){
    global $intArray;
    $intArray="";
    for($i=0;$i<2000;$i++)
        $intArray[]=$i;
    if(is_array($setting)){
        $allkeys=array_keys($setting);
        foreach($allkeys as $aKey)
            cfg_recurse($setting[$aKey], $aKey, $outArray);
    }
    $cfgf=fopen($cfgfile,"w");
    foreach($outArray as $aLine)
        fputs($cfgf,stripslashes($aLine)."\r\n");
    fclose($cfgf);
}

function cfg_recurse($stuffIn, $keysofar, &$toAppend){
    global $intArray, $newline;
    if(is_array($stuffIn)){
        $allkeys=array_keys($stuffIn);
        if(array_slice($intArray,0,sizeof($allkeys))==$allkeys)
            $nokey=true;
        else 
            $nokey=false;
        foreach($allkeys as $aKey){
            if(!$nokey) $toKey=$aKey;    
            cfg_recurse($stuffIn[$aKey], $keysofar."[".$toKey."]", $toAppend);
        }
    }else
        $toAppend[]=$keysofar."=".str_replace("\n",$newline,$stuffIn);
}
?>

Note that these functions support nested arrays of unlimited levels ;)

<< Back to user notes page

To Top