Extract the href from a URL with a class using PHP?

advertisements

Is this even possible...

Say I have some text with a link with a class of 'click':

<p>I am some text, i am some text, i am some text, i am some text
<a class="click" href="http://www.google.com">I am a link</a>
i am some text, i am some text, i am some text, i am some text</p>

Using PHP, get the link with class name, 'click', then get the href value?


There are a few ways to do this, the quickest is to use XPath:

$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

$nodeList = $xpath->query('//a[@class="click"]');
foreach ($nodeList as $node) {
    $href = $node->getAttribute('href');
    $text = $node->textContent;
}