dongshi4773 2013-10-04 15:19
浏览 94
已采纳

PHP DomXPath - 按类获取子项

So far, my code is getting all classes 'forumRow' using a xPath query. How would I get the href-attribute of the a-element which exists once in every 'forumRow' class?

I'm kinda stuck at the point where I can run a query starting from the result of the first query.

My current code

            $this -> boards = array();
            $html = @file_get_contents('http://www.roblox.com/Forum/Default.aspx');

            libxml_use_internal_errors(true);
            $page = new DOMDocument();
            $page -> preserveWhiteSpace = false;
            $page -> loadHTML($html);

            $xpath = new DomXPath($page);
            $board_array = $xpath -> query('//*[@class="forumRow"]');

            foreach($board_array as $board)
            {
                $childNodes = $board -> childNodes;
                $boardName = $childNodes -> item(0) -> nodeValue;

                if (strlen($boardName) > 0)
                {

                    $boardDesc = $childNodes -> item(1) -> nodeValue;
                    array_push($this -> boards, array($boardName, $boardDesc));
                }
            }
            $Cache -> saveData(json_encode($this -> boards));
  • 写回答

2条回答 默认 最新

  • duanpo1498 2013-10-04 15:48
    关注

    Sad to say, I could not get your code to work (regarding extract of forumRow <td>'s) - so I made this up instead :

    $html = @file_get_contents('http://www.roblox.com/Forum/Default.aspx');
    libxml_use_internal_errors(true);
    $page = new DOMDocument();
    $page->preserveWhiteSpace = false;
    $page->loadHTML($html);
    $xpath = new DomXPath($page);
    
    foreach($xpath->query('//td[@class="forumRow"]') as $element){
        $links=$element->getElementsByTagName('a');
        foreach($links as $a) {
            echo $a->getAttribute('href').'<br>';
        }
    }
    

    produces

    /Forum/Search/default.aspx
    /Forum/ShowForum.aspx?ForumID=46
    /Forum/ShowForum.aspx?ForumID=14
    /Forum/ShowForum.aspx?ForumID=44
    /Forum/ShowForum.aspx?ForumID=43
    /Forum/ShowForum.aspx?ForumID=45
    /Forum/ShowForum.aspx?ForumID=21
    /Forum/ShowForum.aspx?ForumID=13
    ...
    a very long list

    All the hrefs from <td class="forumRow">..<a href= ... ></a>..</td>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理
  • ¥15 操作系统相关算法中while();的含义
  • ¥15 CNVcaller安装后无法找到文件
  • ¥15 visual studio2022中文乱码无法解决
  • ¥15 关于华为5g模块mh5000-31接线问题
  • ¥15 keil L6007U报错
  • ¥15 webapi 发布到iis后无法访问
  • ¥15 初学者如何快速上手学习stm32?
  • ¥15 如何自动更换布娃娃图片上的衣服
  • ¥15 心理学eprime编程