How to format var_export to php5.4 array syntax

后端 未结 5 645
北海茫月
北海茫月 2020-12-30 21:37

There are lots of questions and answers around the subject of valid php syntax from var outputs, what I am looking for is a quick and clean way of getting the output of

相关标签:
5条回答
  • 2020-12-30 22:27

    I had something similar laying around.

    function var_export54($var, $indent="") {
        switch (gettype($var)) {
            case "string":
                return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
            case "array":
                $indexed = array_keys($var) === range(0, count($var) - 1);
                $r = [];
                foreach ($var as $key => $value) {
                    $r[] = "$indent    "
                         . ($indexed ? "" : var_export54($key) . " => ")
                         . var_export54($value, "$indent    ");
                }
                return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
            case "boolean":
                return $var ? "TRUE" : "FALSE";
            default:
                return var_export($var, TRUE);
        }
    }
    

    It's not overly pretty, but maybe sufficient for your case.

    Any but the specified types are handled by the regular var_export. Thus for single-quoted strings, just comment out the string case.

    0 讨论(0)
  • 2020-12-30 22:27

    As the comments have pointed out, this is just an additional syntax. To get the var_export back to the bracket style str_replace works well if there are no ) in the key or value. It is still simple though using JSON as an intermediate:

    $output = json_decode(str_replace(array('(',')'), array('&#40','&#41'), json_encode($arr)), true);
    $output = var_export($output, true);
    $output = str_replace(array('array (',')','&#40','&#41'), array('[',']','(',')'), $output);
    

    I used the HTML entities for ( and ). You can use the escape sequence or whatever.

    0 讨论(0)
  • 2020-12-30 22:32

    With https://github.com/zendframework/zend-code :

    <?php
    use Zend\Code\Generator\ValueGenerator;
    $generator = new ValueGenerator($myArray, ValueGenerator::TYPE_ARRAY_SHORT);
    $generator->setIndentation('  '); // 2 spaces
    echo $generator->generate();
    
    0 讨论(0)
  • 2020-12-30 22:36

    I realize this question is ancient; but search leads me here. I didn't care for full iterations or using json_decode, so here's a preg_replace-based var_export twister that gets the job done.

    function var_export_short($data, $return=true)
    {
        $dump = var_export($data, true);
    
        $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
        $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
        $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
    
        if (gettype($data) == 'object') { // Deal with object states
            $dump = str_replace('__set_state(array(', '__set_state([', $dump);
            $dump = preg_replace('#\)\)$#', "])", $dump);
        } else { 
            $dump = preg_replace('#\)$#', "]", $dump);
        }
    
        if ($return===true) {
            return $dump;
        } else {
            echo $dump;
        }
    }
    

    I've tested it on several arrays and objects. Not exhaustively by any measure, but it seems to be working fine. I've made the output "tight" by also compacting extra line-breaks and empty arrays. If you run into any inadvertent data corruption using this, please let me know. I haven't benchmarked this against the above solutions yet, but I suspect it'll be a good deal faster. Enjoy reading your arrays!

    0 讨论(0)
  • 2020-12-30 22:36

    For anyone looking for a more modern-day solution, use the Symfony var-exporter, also available as a standalone library on composer, but included in Symfony default.

    composer require symfony/var-exporter
    
    use Symfony\Component\VarExporter\VarExporter;
    
    // ...
    
    echo VarExporter::export($arr)
    
    0 讨论(0)
提交回复
热议问题