删除var_export()php的格式 [英] Remove formatting of var_export() php
问题描述
我使用以下命令将数据数组打印到保存为.php的文件中,以便以后使用include来获取数组。
I am using the following command to print an array of data to a file saved as .php so i can use include to grab the array later.
$toFile = '$Data = '. var_export($DataArray,true).'; ';
file_put_contents( $filename.'.php', "<?php ".$toFile." ?>");
它被打印到格式化的文件中,以便读取,但最终占用很多由于空格和换行符等,磁盘上的空间更多。有没有简单的方法来删除格式,所以占用更少的空间。我想使用str_replace这将适用于新的行,但由于数据可能会有空格的空间不能。
It is printed to the file formatted to make it easy to read but it ends up taking up a lot more space on the disk due to spaces and newline and such. Is there an easy way to remove the formatting so it take up less space. I thought of using str_replace which would work for new lines but not spaces due to the data might have spacing in it.
<?php $Data = array (
'Info' =>
array (
'value1' => 'text here',
'value2' => 'text here',
'value3' => '$2,500 to $9,999',
), ....
就像这样
<?php $Data = array('Info'=>array('value1'=>'text here','value2'=>'text here','value3'=>'$2,500 to $9,999'),...
谢谢
编辑:有没有一个preg_replace模式我可以用来删除不需要的空格只有引号外?
Is there a preg_replace pattern i can use to remove unwanted spaces ONLY outside of quotes?
推荐答案
所以我只是写了一个小函数返回缩小的PHP输出,并在我的p retty过于简化的测试用例,它节省了大约50%的空间 - 趋势较大的数组应该是一个显着更高的百分比
So I just wrote a little function that returns minified PHP-output and in my pretty oversimplified test case it saved about 50% space - tendency for larger arrays should be a significantly higher percentage
<?php
function min_var_export($input) {
if(is_array($input)) {
$buffer = [];
foreach($input as $key => $value)
$buffer[] = var_export($key, true)."=>".min_var_export($value);
return "[".implode(",",$buffer)."]";
} else
return var_export($input, true);
}
$testdata=["test","value","sub"=>["another","array" => ["meep"]]];
$d1 = var_export($testdata, true);
$d2 = min_var_export($testdata);
echo "$d2\n===\n$d1\n\n";
printf("length old: %d\nlength new: %d\npercent saved: %5.2f\n", strlen($d1),strlen($d2), (1-(strlen($d2)/strlen($d1)))*100);
这篇关于删除var_export()php的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!