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条)

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波