Question

I have the following:

$html = "<a href="/path/to/page.html" title="Page name"><img src="path/to/image.jpg" alt="Alt name"  />Page name</a>" 

I need to extract href and src attribute and anchor text

My solution:

$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('a') as $node) { 
    $href = $node->getAttribute('href');
    $title = $node->nodeValue;
}
foreach ($dom->getElementsByTagName('img') as $node) { 
    $img = $node->getAttribute('src');
}

What would be the smarter way?

Was it helpful?

Solution

You can avoid the loops if you use DOMXPath to grab the elements directly:

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

$a = $xpath->query( '//a')->item( 0);         // Get the first <a> node
$img = $xpath->query( '//img', $a)->item( 0); // Get the <img> child of that <a>

Now, you can do:

echo $a->getAttribute('href');
echo $a->nodeValue;
echo $img->getAttribute('src');

This will print:

/path/to/page.html 
Page name 
path/to/image.jpg 

OTHER TIPS

Possible alternative approach:

$domXpath = new DOMXPath(DOMDocument::loadHTML($html));
$href = $domXpath->query('a/@href')->item(0)->nodeValue;
$src = $domXpath->query('img/@src')->item(0)->nodeValue;

Empty/null checks are up to you.

http://ca2.php.net/manual/en/function.preg-match.php - if you want to use regex

or

http://php.net/manual/en/book.simplexml.php

if you need to use xml parsing.

// Simple xml
$xml = simplexml_load_string($html);

$attr = $xml->attributes();
echo 'href: ' . $attr['href'] . PHP_EOL;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top