Monday, May 18, 2009

array to file

Code reads an array and writes array's php code to a file.
Inputs:array_to_file($array array,$arrayname string,$filename string)
Returns:none (writes file)


/* Array to File */
function __process_array($array,$indent)
{
$ret_str = "";
$first = true;
foreach ($array as $key => $value)
{

if (!$first)
$ret_str .= ",\n";
else
$first = false;

$ret_str .= str_repeat(" ",$indent);

if (is_array($value))
{
$ret_str .= "'$key' => array(\n".__process_array($value,$indent+5)."\n".str_repeat(" ",$indent).")";
}
elseif (is_string($value))
{
$ret_str .= "'$key' => '$value'";
}
elseif (is_int($value))
{
$ret_str .= "'$key' => $value";
}
elseif (is_bool($value))
{
$ret_str .= "'$key' => ".($value?"true":"false");
}
}
return $ret_str;
}

function array_to_file($array,$name,$filename)
{
$file_str = "
$file_str .= __process_array($array,6);
$file_str .= "\n );\n?>";

$file = fopen($filename,"w");
fwrite($file,$file_str);
fclose($file);
}
?>

1 comment:

  1. waw.. very good information.
    nice info thank you bro,,,

    ReplyDelete