【问题标题】:Simple HTML DOM getting href and anchor text from within heading简单的 HTML DOM 从标题中获取 href 和锚文本
【发布时间】:2015-12-03 02:45:59
【问题描述】:

对于初学者,这是我拥有的代码

    <?php
    include ('parser_class.php');
        $source = file_get_html('http://www.billboard.com/search/site/awards?f[0]=ss_bb_type%3Aarticle');
        $title = $source->find('h3.title'); //getting song title
    ?>
    <div id="awar">
    <?php
        if ($title){
            $title = array_slice($title, 0, 10);
            foreach($title as $titles){
                $links = $titles->href;
                $string = $titles->innertext;
                //$string = (strlen($string) > 75) ? substr($string,0,72).'...' : $string;
    ?>
            <center>
            <table style="width: 100%;">
                <tr>
                    <td style="width: 50%; text-align: left; padding-left: 5px;"><span class="song"><?php echo $string ?></span></td><td style="width: 25%; text-align: left; padding-left: 5px;"><a href="http://www.billboard.com<?php echo $links ?>" class="download">Read Article</a></td>
                </tr>
            </table>
            </center>
            <hr class="betw" />

    <?php
            }
        }
        else{
            echo"<p class='song'>No Articles Found</p>";
        }
    ?>

由于该网站的链接上没有类,我不得不从类似的东西中提取我的信息

<h3 class="title"> <a href="/articles/columns/country/6784891/lady-antebellum-charles-kelley-steps-out-on-his-own">Lady Antebellum's Charles Kelley Steps Out On His Own In New York City</a> </h3>

呼叫innertext 我得到了h3 中的所有内容

我需要弄清楚如何从h3 中分别获取hrefanchor text

有没有办法从innertext 中获取href,然后是hrefinnertext

我希望这个网站在他们的链接上有一个类,因为这当然会让这件事变得更容易。我已经毫无问题地使用了这些功能,因为网站实际上在其链接上使用了类,但看起来广告牌决定让我的事情变得更难!

我们将不胜感激。

注意:我的parser_class.php 是位于here 的那个

【问题讨论】:

    标签: php dom html-parsing


    【解决方案1】:

    您必须选择锚点,而不是 h3title。所以h3.title a 现在从那个锚点你会得到hrefanchor text。为了获得 href,您可以从锚 html 创建 SimpleXMLElement 对象。

     <?php
        include ('parser_class.php');
        $source = file_get_html('http://www.billboard.com/search/site/awards?f[0]=ss_bb_type%3Aarticle');
        foreach ($source->find('h3.title a') as $anchor) {
            $anch = new SimpleXMLElement($anchor);
            echo "Anchor text is : ".$anch;
            echo "<br>";
            echo "href is : ";
            echo $link_href = $anch['href'];
            echo "<hr>";
        }
      ?>
    

    【讨论】:

    • 工作得非常好,非常感谢你,我觉得很可笑,这是一个我无法弄清楚的简单修复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    相关资源
    最近更新 更多