解析具有img标签作为子元素的锚标签

时间:2013-06-28 05:06:29

标签: php domxpath domparser

我需要找到所有锚标记,其中img标记为子元素。考虑以下情况,

<a href="test1.php">
 <img src="test1.jpg" alt="Test 1" />
</a>

<a href="test2.php">
 <span>
  <img src="test2.jpg" alt="Test 2" />
 </span>
</a>

我的要求是生成href属性列表以及srcalt 即,

$output = array(
 array(
  'href' => 'test1.php',
  'src'  => 'test1.jpg',
  'alt'  => 'Test 1'
 ),
 array(
  'href' => 'test2.php',
  'src'  => 'test2.jpg',
  'alt'  => 'Test 2'
 )
);

如何在PHP中匹配上述情况? (使用Dom Xpath或任何其他dom解析器)

提前致谢!

3 个答案:

答案 0 :(得分:3)

假设$doc是代表您的HTML文档的DOMDocument

$output = array();
$xpath = new DOMXPath($doc);
# find each img inside a link
foreach ($xpath->query('//a[@href]//img') as $img) {

    # find the link by going up til an <a> is found
    # since we only found <img>s inside an <a>, this should always succeed
    for ($link = $img; $link->tagName !== 'a'; $link = $link->parentNode);

    $output[] = array(
        'href' => $link->getAttribute('href'),
        'src'  => $img->getAttribute('src'),
        'alt'  => $img->getAttribute('alt'),
    );
}

答案 1 :(得分:0)

使用简单的HTML DOM解析器http://simplehtmldom.sourceforge.net/

您可以执行以下操作(粗略代码,您必须调整代码才能使其正常工作。):

 //include simple html dom parser
 $html = file_get_html('your html file here');

foreach($html->find('a') as $data){
   $output[]['href']=$data->href;
   $output[]['src']=$data->src;
   $output[]['alt']=$data->alt;

}

答案 2 :(得分:0)

假设您的HTML是有效的XML文档(具有单个根节点等),您可以像这样使用SimpleXML:

$xml = simplexml_load_file($filename);
$items = array();
foreach ($xml->xpath('//a[@href]') as $anchor) {
    foreach ($anchor->xpath('.//img[@src][@alt]') as $img) {
        $items[] = array(
            'href' => (string) $anchor['href'],
            'src' => (string) $img['src'],
            'alt' => (string) $img['alt'],
        );
    }
}
print_r($items);

这使用xpath在文档中搜索具有<a>属性的所有href标记。然后,它会在找到的每个<a>标记下进行搜索,以查找同时包含<img>src个标记的alt个标记。然后它只是抓取所需的属性并将它们添加到数组中。

相关问题