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 echarts绘制图表
  • ¥15 根据企业名称 对照两个文件 样本筛选/匹配
  • ¥15 Linux环境下CA证书更新问题
  • ¥15 sqlserver语句提取结果以外数据
  • ¥60 微信小程序如何上传QQ聊天文件
  • ¥300 开发的系统遭到无良商家的破解,请问如何防止再次发生,并追回损失
  • ¥15 java代码写在记事本上后在cmd上运行时无报错但又没生成文件
  • ¥15 关于#python#的问题:在跑ldsc数据整理的时候一直抱这种错误,要么--out识别不了参数,要么--merge-alleles识别不了参数(操作系统-linux)
  • ¥15 PPOCRLabel
  • ¥15 混合键合键合机对准标识