我正在尝试获取网站中的所有菜单项。我试过的代码是
include("simple_html_dom.php");
$html = dlPage('http://www.homeshop18.com/');
$htmlpage=new simple_html_dom();
$htmlpage->load($html);
$count=1;
foreach($htmlpage->find('ul#nav') as $li){
echo $count;
$count++;
}
ul#nav中有10个li元素,但我得到的计数总是1.为什么?
答案 0 :(得分:0)
如果您尝试遍历一组嵌套的ul
元素,则可以使用如下函数:
$html = file_get_html('http://www.homeshop18.com/');
$ulnav = $html->find('ul#nav', 0); // target the ul first
get_nested_lis( $ulnav );
function get_nested_lis( $ul ) {
# get the children of the ul element
foreach ($ul->children() as $li) {
# get the children of each of those li elements
foreach ($li->children() as $child) {
# if the element is an 'a', print the contents
if ($child->tag === 'a') {
# we have a link
echo "Link: " . $child->plaintext . "\n";
}
# if the element is another ul, call the function on that ul
elseif ($child->tag === 'ul') {
get_nested_lis( $child );
}
}
}
}
但是,您尝试遍历的页面上的菜单是由javascript生成的,因此如果您想遍历该结构,则必须复制浏览器生成的源并在其上运行脚本。