Created
April 20, 2012 15:20
-
-
Save Naatan/2429566 to your computer and use it in GitHub Desktop.
Tries to convert a PHP variable of any type to yaml. This is EXTREMELY experimental, I'm just playing around.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function renderYaml($result, $prefix = '', $indentation = 0, $ptype = '') | |
{ | |
$result = json_decode(json_encode($result)); // convert key based arrays to objects | |
$indent = $prefix; | |
for ($c=0;$c<$indentation; $c++) { | |
$indent = ' ' . $indent; | |
} | |
$type = gettype($result); | |
switch ($type) | |
{ | |
case 'boolean': | |
echo ($result ? 'ON' : 'OFF'); | |
break; | |
case 'string': | |
if (strpos($result, "\n") !== false) | |
{ | |
echo "|\n" . $indent; | |
$result = str_replace("\n", "\n" . $indent, $result); | |
} | |
echo $result; | |
break; | |
case 'integer': | |
case 'double': | |
echo $result; | |
break; | |
case 'array': | |
$first = true; | |
if ($ptype == 'object') { | |
echo "\n"; | |
$first = false; | |
} | |
foreach ($result AS $v) | |
{ | |
if ( ! $first) echo $indent; | |
echo '- '; | |
$this->renderYaml($v, $prefix . ' ', $indentation, $type); | |
$first = false; | |
} | |
break; | |
case 'object': | |
$first = true; | |
if ($ptype == 'object') { | |
echo "\n"; | |
$first = false; | |
} | |
foreach ($result AS $k => $v) | |
{ | |
if ( ! $first) echo $indent; | |
echo $k . ': '; | |
$this->renderYaml($v, $prefix, $indentation + 1, $type); | |
$first = false; | |
} | |
break; | |
default: | |
echo $type; | |
break; | |
} | |
echo "\n"; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment