Pulling an HREF using only DomDocument

I would like to pull the HREF from the following html output

<div class="course">
    <p class="course-data">
        <a class="course-name i13n-sec-country i13n-ltxt-meeting i13n-tab-TODO-TAG-TAB" href="/course?courseId=1.2&amp;date=20150713">
            Ayr
        </a> | SOFT
    </p>
    <ul>
        <li class="full" title="7f 50yds Maiden Stakes | 10 runners">
            <a class="i13n-sec-country i13n-ltxt-race i13n-tab-TODO-TAG-TAB" href="/raceresult?raceId=1.2.1150713.1">
                09:00
            </a>
        </li>
        <li class="full" title="1m Handicap | 5 runners">
            <a class="i13n-sec-country i13n-ltxt-race i13n-tab-TODO-TAG-TAB" href="/raceresult?raceId=1.2.1150713.2">
                09:30
            </a>
        </li>
        <li class="full" title="1m2f Handicap | 6 runners">
            <a class="i13n-sec-country i13n-ltxt-race i13n-tab-TODO-TAG-TAB" href="/raceresult?raceId=1.2.1150713.3">
                10:00
            </a>
        </li>

      

But I only need the href attribute if the call contains the word "race" - for example it would pull this href

<a class="i13n-sec-country i13n-ltxt-race i13n-tab-TODO-TAG-TAB" href="/raceresult?raceId=1.2.1150713.1">

      

I tried myself but can't seem to pull the href with getAttribute('href')

and get the error "Call member function member () for non-object"

+3


source to share


1 answer


I think this is what you are looking for

$dom = new DomDocument;
$dom->loadHtml($html);
$tagList = $dom->getElementsByTagName('a');
foreach ($tagList as $tag) {
    // Simple string check, but beware using strstr and utf-8
    if(strstr($tag->getAttribute('class'), 'race')) {
        echo $tag->getAttribute('href');
    }
}

      



or you can use SimpleXML

$dom = new DomDocument;
$dom->loadHtml($html);
$xml = simplexml_import_dom($dom);
$tagList = $xml->xpath("//a[contains(@class,'race')]");
foreach ($tagList as $tag) {
    var_dump($tag->attributes()['href']);
}

      

+3


source







All Articles