Reputation: 769
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&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 want the href attribute if the call contains the word "race" - for eg 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 have tried myself but cant seem to pull the href using getAttribute('href')
and get the error "Call to a member function item() on a non-object"
Upvotes: 2
Views: 42
Reputation: 657
I think this is what your 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']);
}
Upvotes: 2