使用JSON在PHP中填充下拉菜单

时间:2012-01-16 00:32:49

标签: php json

我在文件menu.txt中有以下JSON:

[{
"title":"About",
"url":"/about",
"nodes":[
    {"title":"Staff","url":"/about/staff"},
    {"title":"Location","url":"/about/location"}
]},{
"title":"Contact",
"url":"/contact"
}]

使用以下Javascript:

var menu = // JSON from menu.txt

function parseNodes(nodes) {
    var ul = document.createElement('UL');
    for(var i=0; i < nodes.length; i++) {
        ul.appendChild(parseNode(nodes[i]));
    }
    return ul;
}
function parseNode(node) { // takes a node object and turns it into a <li>
    var li = document.createElement('LI');
    var a = ('<a href="'+node.url+'">'+node.title+'</a>');
    li.innerHTML = a;
    if(node.nodes) li.appendChild(parseNodes(node.nodes));
    return li;
}
document.getElementById('menu').appendChild(parseNodes(menu));

我可以创建以下HTML:

<div id="menu">
    <ul>
        <li><a href="/about">About</a></li>
            <ul>
                <li><a href="/about/staff">Staff</a></li>
                <li><a href="/about/location">Location</a></li>
            </ul>
        </li>
        <li><a href="/contact">Contact</a></li>
    </ul>
</div>

有没有一种简单的方法可以在PHP中执行此操作,以便更加适合搜索引擎?最好是我可以在我的页面中包含menu.php的PHP脚本吗?

<?php

$file = "menu.txt";

$json = json_decode(file_get_contents($file), true);

// ????

?>

1 个答案:

答案 0 :(得分:3)

这应该让你开始;)

<?php
function parseNodes($nodes) {
        $ul = "<ul>\n";
        foreach ($nodes as $node) {
                $ul .= parseNode($node);
        }
        $ul .= "</ul>\n";
        return $ul;
}

function parseNode($node) {
        $li = "\t<li>";
        $li .= '<a href="'.$node->url.'">'.$node->title.'</a>';
        if (isset($node->nodes)) $li .= parseNodes($node->nodes);
        $li .= "</li>\n";
        return $li;
}


$json = '[{
"title":"About",
"url":"/about",
"nodes":[
    {"title":"Staff","url":"/about/staff"},
    {"title":"Location","url":"/about/location"}
]},{
"title":"Contact",
"url":"/contact"
}]';
$nodes = json_decode($json);

$html = parseNodes($nodes);
echo $html;