note 46481 added to function.parse-str

From: Date: Tue, 12 Oct 2004 23:10:59 +0000
Subject: note 46481 added to function.parse-str
Groups: php.notes 
Request: Send a blank email to php-notes+get-78454@lists.php.net to get a copy of this message
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 ;) ---- Manual Page -- http://www.php.net/manual/en/function.parse-str.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+46481 Delete -- http://master.php.net/manage/user-notes.php?action=delete+46481&report=yes Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+46481&report=yes&reason=bad+code Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+46481&report=yes&reason=spam Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+46481&report=yes&reason=useless+example Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+46481&report=yes&reason=contains+commercial+links Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+46481&report=yes&reason=useless+note Reject -- http://master.php.net/manage/user-notes.php?action=reject+46481&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#78454) next »