1

我正在使用以下命令将数据数组打印到另存为 .php 的文件中,以便以后可以使用 include 来获取数组。

$toFile = '$Data = '. var_export($DataArray,true).'; ';
file_put_contents( $filename.'.php', "<?php ".$toFile." ?>");

它被打印到格式化为易于阅读的文件中,但由于空格和换行符等原因,它最终占用了磁盘上的更多空间。有没有一种简单的方法可以删除格式以减少占用空间。我想过使用 str_replace ,它适用于新行但不适用于空格,因为数据中可能有空格。

<?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 模式可以用来仅在引号之外删除不需要的空格?

4

2 回答 2

4

抱歉,问题仍然存在:我有同样的“问题”,我认为 JSON 不是我的答案,因为 PHP-Array 的解析效率比 JSON 对象高得多。

所以我只写了一个小函数,它返回缩小的 PHP 输出,在我非常简单的测试用例中,它节省了大约 50% 的空间 - 更大数组的趋势应该是显着更高的百分比

<?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);
于 2016-02-08T08:39:53.827 回答
1

json_encode()ing the data might be a better approach. That condenses it down really small and there's even a function json_decode() to convert it back to an array.

Alternatively, print_r() has a second parameter that allows you to return it's output as a string. From there you can condense it yourself.

With var_dump() you could possibly do it using output buffering. Start output buffer using ob_start() and then use var_dump() as normal. Use ob_get_clean() to get the output of var_dump() and from there you can start removing all unnecessary characters.

于 2013-10-15T16:26:41.740 回答