Print array as code

I want to convert a large yaml file to an array of PHP source code . I can read yaml code and return a PHP array, but with var_dump ($ array) I get pseudocode as output. I would like to print the array as a valid php code, so I can copy it to my project and cut yaml.

+51
php yaml
Feb 28 '11 at 8:25
source share
4 answers

You are looking for var_export .

+106
Feb 28 '11 at 8:27
source share

You can use var_export , serialize (with unserialize at the end of the reservation) or even json_encode (and use json_decode on the receiving side). The latter has an advantage in the release, which can be handled by anyone that can handle JSON.

+3
Feb 28 '11 at 8:44
source share

I donโ€™t know why, but I could not find a satisfying code anywhere.

He wrote it quickly. Let me know if you find any errors.

  function printCode($array, $path=false, $top=true) { $data = ""; $delimiter = "~~|~~"; $p = null; if(is_array($array)){ foreach($array as $key => $a){ if(!is_array($a) || empty($a)){ if(is_array($a)){ $data .= $path."['{$key}'] = array();".$delimiter; } else { $data .= $path."['{$key}'] = \"".htmlentities(addslashes($a))."\";".$delimiter; } } else { $data .= printCode($a, $path."['{$key}']", false); } } } if($top){ $return = ""; foreach(explode($delimiter, $data) as $value){ if(!empty($value)){ $return .= '$array'.$value."<br>"; } }; return $return; } return $data; } //REQUEST $x = array('key'=>'value', 'key2'=>array('key3'=>'value2', 'key4'=>'value3', 'key5'=>array())); echo printCode($x); //OUTPUT $array['key'] = 'value'; $array['key2']['key3'] = 'value2'; $array['key2']['key4'] = 'value3'; $array['key2']['key5'] = array(); 

Hope this helps someone.

+2
Jan 25 '13 at 8:57
source share

Another way to display the array as indented code.

Tested only with an array that contains a string, an integer and an array.

 function bo_print_nice_array($array){ echo '$array='; bo_print_nice_array_content($array, 1); echo ';'; } function bo_print_nice_array_content($array, $deep=1){ $indent = ''; $indent_close = ''; echo "["; for($i=0; $i<$deep; $i++){ $indent.='&nbsp;&nbsp;&nbsp;&nbsp;'; } for($i=1; $i<$deep; $i++){ $indent_close.='&nbsp;&nbsp;&nbsp;&nbsp;'; } foreach($array as $key=>$value){ echo "<br>".$indent; echo '"'.$key.'" => '; if(is_string($value)){ echo '"'.$value.'"'; }elseif(is_array($value)){ bo_print_nice_array_content($value, ($deep+1)); }else{ echo $value; } echo ','; } echo '<br>'.$indent_close.']'; } 
0
Jul 23 '19 at 10:29
source share



All Articles