Remove formatting of var_export() php

杀马特。学长 韩版系。学妹 提交于 2019-12-11 09:44:57

问题


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." ?>");

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',
  ), ....

to something like this

<?php $Data = array('Info'=>array('value1'=>'text here','value2'=>'text here','value3'=>'$2,500 to $9,999'),...

Thanks

EDIT: Is there a preg_replace pattern i can use to remove unwanted spaces ONLY outside of quotes?


回答1:


Sorry for necroing, but if the question still is open: I had the same "problem", and I don't think JSON is the answer in my case because a PHP-Array just parses much more efficiently than a JSON-object.

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);



回答2:


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.



来源:https://stackoverflow.com/questions/19386252/remove-formatting-of-var-export-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!