Skip to content

Instantly share code, notes, and snippets.

@Naatan
Created April 20, 2012 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Naatan/2429566 to your computer and use it in GitHub Desktop.
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.
<?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