0

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?

4

3 に答える 3

1

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 
于 2012-12-13T18:00:15.247 に答える
0

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;
于 2012-12-13T17:55:28.333 に答える
0

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.

于 2012-12-13T18:01:17.857 に答える