note 95081 added to function.fwrite

From: Date: Sat, 12 Dec 2009 16:47:31 +0000
Subject: note 95081 added to function.fwrite
Groups: php.notes 
Request: Send a blank email to php-notes+get-163880@lists.php.net to get a copy of this message
Here are the two function I use to save my arrays to a file and load them into exactly the same array as it was before. At the moment I have no need in saving ressources or something. There I guess a memory-dump and -load is needed. <?php function save_array_to_file($filename,$b) { if (!is_resource($filename)) { if (!$file = fopen($filename,'w+')) return false; } else { $file = $filename; } foreach ($b as $key=>$val) { fwrite($file,(is_int($key) ? chr(6).(string)$key : chr(5).$key)); if (is_array($val)) { fwrite($file,chr(0)); //array starts save_array_to_file($file,$val); fwrite($file,chr(1)); //array ends } elseif (is_int($val)) { fwrite($file,chr(2).(string) $val); //int } elseif (is_string($val)) { fwrite($file,chr(3).$val); //string } } if (!is_resource($filename)) fclose($file); return true; } function read_array_from_file($filename) { if (!is_resource($filename)) { if (!$file = fopen($filename,'r')) return false; } else { $file = $filename; } $ret=array(); $key=''; $val=null; $mod=0; while (!feof($file)) { $b = fread($file,1); if (ord($b) < 9) { if ($val!=null) { if ($mod==2) $val=(int) $val; if ($mod==3) $val=(string) $val; $ret[$key]=$val; $key=''; $val=null; $mod=0; } else { if (ord($b)==0) $mod=0; elseif (ord($b)==1) return $ret; else { if ($mod==5) $key=(string) $key; if ($mod==6) $key=(int) $key; $mod=ord($b); } } } else { if ($mod==5 || $mod==5) $key.=$b; elseif ($mod==0) $val=read_array_from_file($file); else $val.=$b; } } if (!is_resource($filename)) fclose($file); return $ret; } ?> ---- Server IP: 212.124.37.9 Probable Submitter: 80.144.66.121 ---- Manual Page -- http://www.php.net/manual/en/function.fwrite.php Edit -- https://master.php.net/note/edit/95081 Del: integrated -- https://master.php.net/note/delete/95081/integrated Del: useless -- https://master.php.net/note/delete/95081/useless Del: bad code -- https://master.php.net/note/delete/95081/bad+code Del: spam -- https://master.php.net/note/delete/95081/spam Del: non-english -- https://master.php.net/note/delete/95081/non-english Del: in docs -- https://master.php.net/note/delete/95081/in+docs Del: other reasons-- https://master.php.net/note/delete/95081 Reject -- https://master.php.net/note/reject/95081 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#163880) next »