PHP数组转TOML

几年前的代码,稍微修改得好看一点。

<?php
/**
 * PHP数组转Toml
 *
 * beiliwenxiao
 *
 * 2014_07_09初稿
 * 2017_06_27修改
 *
 * */
$show = "";

function getToml($arr, $title = "")
{
    global $show;
    if (is_array($arr)) {
        foreach ($arr as $key => $value) {
            if (is_array($value)) {

                $show .= "\r\n";
                if (!empty($title)) {
                    $show .= "[" . $title . '.' . $key . "]\r\n";
                } else {
                    $show .= "[" . $key . "]\r\n";
                }

                $show .= getToml($value, $key);
            } else if (!empty($value) || $value === false) {

                $show .= "\r\n";
                $show .= $key . "=\"" . getRightString($value) . "\"\r\n";
            }

        }
    }


}

function getRightString($str)
{
    $value = $str;
    if ($value === true) {
        $value = "true";
    }
    if ($value === false) {
        $value = "false";
    }

    $value = addslashes($value);
    $value = str_replace("\'", "'", $value);

    return $value;
}

$test = '{
    "dog": {
        "onekey": "onevalue",
        "tater": {
            "type": "pug"
        }
    }
}';

$test = json_decode($test, true);
getToml($test);
echo $show;

 

posted @ 2017-06-27 00:52  北里闻箫  阅读(543)  评论(0编辑  收藏  举报