首页 > 代码库 > PHP数组转TOML

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;

 

PHP数组转TOML