简单的HTML DOM从标题内获取href和锚文本

时间:2015-12-03 02:46:00

标签: php dom html-parsing

首先,这是我的代码

    <?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

内的所有内容

我需要弄清楚如何在href

内单独获取anchor texth3

有没有办法从href获得innertext,然后从innertext获取href

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

非常感谢正确方向上的一点。

注意:我的parser_class.php位于here

1 个答案:

答案 0 :(得分: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>";
    }
  ?>