我对php非常熟悉。我想动态创建一个带有菜单的页面。
如果在我的代码中有:
<section id="one" >...</section>
<section id="two" >...</section>
<section id="three" >...</section>
我想生成这个菜单:
<li ><a id="menu-one" href="#one"> <span> One </span></a></li>
<li ><a id="menu-two" href="#two"> <span> Two </span></a></li>
<li ><a id="menu-three" href="#three"> <span> Three </span></a></li>
这很容易,但我尝试过这种方式,但没有成功:
$html = file_get_html('http://mysite.it');
foreach($html->find('section') as $element){
$idSection=$element->id;
$menuElement .= '<li><a id="menu-'.$idSection.'" href="#'.$idSection.'" ><span>'.$idSection.'</span></a></li>';
echo '<ul>'.$menuElement.'</ul>';
}
EDIT:这可以生成一个节数组,但不起作用。它错了吗?
$els = $document->getElementsByTagName('section');
谢谢!
现在您有了一个ul和多个li
echo '<ul>'
foreach($html->find('section') as $element){
$idSection=$element->id;
$menuElement .= '<li><a id="menu-'.$idSection.'" href="#'.$idSection.'" ><span>'.$idSection.'</span></a></li>';
echo $menuElement;
}
echo '</ul>'
我想你想要这样的东西。。。
$sections = array(
'one' => 'Something',
'two' => 'Something Else',
'three' => 'Something Awesome'
);
// output <section>s
foreach ($sections as $k=>$v) {
echo '<section id="'. $v .'">'. $v .'</section>';
}
// output menu
foreach ($sections as $k=>$v) {
echo '<li ><a id="menu-'. $k .'" href="#'. $k .'"> <span>'. $v .'</span></a></li>';
}
尝试对neokio代码进行一点更改,以获得您想要的gor:
$sections = array('one','two','three');
// output <section>s
foreach ($sections as $section) {
echo '<section id="'. $section .'"><li ><a id="menu-'. $section .'" href="#'. $section .'"> <span>'. $section .'</span></a></li></section>';
}