doucao1066 2014-12-02 16:43
浏览 79
已采纳

php DOMDocument - 将子元素列出到数组

For the following HTML:

<html>
<body>
<div whatever></div>
<div id="archive-wrapper">
<ul class="archive-list">
    <li><div><a href="#1">A</a></div></li>
    <li><div><a href="#2">B</a></div></li>
    <li><div><a href="#3">C</a></div></li>
</ul>
</div>
</body>

How could I retrieve, with PHP DOMDocument (http://php.net/manual/es/class.domdocument.php), an array containing (#1,#2,#3) in the most effective way? It's not that I did not try anything or that I want an already done code, I just need to know some guidelines to do it and understand it on my own. Thanks :)

  • 写回答

3条回答 默认 最新

  • dpfad62426 2014-12-02 17:15
    关注

    A simple example using php DOMDocument -

    <?php
    $html = <<<HTML
    <html>
    <body>
    <div whatever></div>
    <div id="archive-wrapper">
    <ul class="archive-list">
        <li><div><a href="#1">A</a></div></li>
        <li><div><a href="#2">B</a></div></li>
        <li><div><a href="#3">C</a></div></li>
    </ul>
    </div>
    </body>
    HTML;
    
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    
    //get all links
    $links = $dom->getElementsByTagName('a');
    $linkArray = array();
    
    //loop through each link
    foreach ($links as $link){
        $linkArray[] = $link->getAttribute('href');
    }
    

    edit
    to get only the links inside ul->li, you could do something like -

    $dom = new DOMDocument();
    $dom->loadHTML($html);
    
    $linkArray = array();
    
    foreach ($dom->getElementsByTagName('ul') as $li){
        foreach ($li->getElementsByTagName('li') as $a){
            foreach ($a->getElementsByTagName('a') as $link){
                $linkArray[] = $link->getAttribute('href');
            }
        }
    }
    

    or if you just want the 1st ul you could simplify to

    //get 1st ul using ->item(0)
    $ul = $dom->getElementsByTagName('ul')->item(0);
    foreach ($ul->getElementsByTagName('li') as $li){
        foreach ($li->getElementsByTagName('a') as $a){
            $linkArray[] = $a->getAttribute('href');
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,