0

好的,所以我使用http://simplehtmldom.sourceforge.net/上的基于 php 的 simple_html_dom.php 来抓取网页,我想做的是生成一个嵌套列表,它反映了 html 元素结构页。最终,我计划使用该列表初始化 jsTree,但我无法通过第一步。我知道有一个简单直接的解决方案,但我似乎无法弄清楚。我花了几个小时在网上搜索,最后才在这里发帖。

本质上我想转换它:

<body>
    <div id='div0'>
        <span id='span0'> <img id='img1'> </span>
    </div>

    <div id='div1'>
        <span id='span1'>  </span>
    </div>
</body>

进入这个:

<ul>
    <li>
        div0
        <ul>
            <li>
                span0
                <ul>
                    <li>
                        img1
                    </li>
                </ul>
           </li>
        </ul>
    </li>
    <li>
        div1
        <ul>
            <li>
                span1
            </li>
        </ul>
    </li>
</ul>

我认为正确的一个例子是这样,但它会生成:`

<li><li>`Fatal error: Call to a member function children() on a non-object in main.php on line 46 

编码:

include_once('simple_html_dom.php');

$html = file_get_html("http://www.thefuckingweather.com/");

function create($url)
{
    print "<li>";
    $count = 0;

    foreach ($url as $chi)
    {
        if($chi->tag != "script")
        {
            if (count($chi->children()) > 0)  //#46
            {
                create($chi->children($count));
            }
            else
            {
                print "</li>";
            }
        }
        $count++;
    }   
}

create($html->find("body"));
4

1 回答 1

0

弄清楚了。我发誓,这可能是因为我太累了。答案非常简单。

include_once('simple_html_dom.php');

$html = file_get_html("http://www.reddit.com/");

foreach ($html->find("body") as $chi)
{
    test($chi);
}

$count = 0;

function test($t)
{
    print "<ul>";
    for ($i = 0; $i < count($t->children()); $i++)
    {
        print "<li>";
        print $t->children($i)->id . " - " . $t->children($i)->tag . $count++;
        test($t->children($i));
        print "</li>";
    }
    print "</ul>";
}
于 2011-03-27T21:51:15.690 回答