0

我有以下内容:

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

我需要提取 href 和 src 属性和锚文本

我的解决方案:

$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');
}

更聪明的方法是什么?

4

3 回答 3

1

如果您使用DOMXPath直接抓取元素,则可以避免循环:

$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>

现在,您可以执行以下操作:

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

这将打印:

/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

可能的替代方法:

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

空/空检查由您决定。

于 2012-12-13T18:01:17.857 回答