note 95081 deleted from function.fwrite by googleguy
| From: | googleguy@php.net | Date: | Tue, 22 Oct 2013 06:49:00 +0000 |
| Subject: | note 95081 deleted from function.fwrite by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-196654@lists.php.net to get a copy of this message | ||
Note Submitter: chaly
----
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;
}
?>