0
我有一個文件menu.txt
以下JSON:填充下拉菜單從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中做到這一點,以便更好的搜索引擎友好?最好是一個PHP腳本,我可以在我的頁面中包含menu.php
?
<?php
$file = "menu.txt";
$json = json_decode(file_get_contents($file), true);
// ????
?>
完美!非常感謝! – Josiah 2012-01-16 04:15:33