解析具有img标记作为子元素的定位标记

解析具有img标记作为子元素的定位标记

问题描述:

我需要找到所有定位标记,其中有一个img标记作为子元素。考虑下面的情况下,解析具有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> 

我的要求是与srcalt

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

我怎样才能符合上述情况在PHP中生成沿的href属性列表? (使用Dom Xpath或任何其他dom解析器)

在此先感谢!

假设$docDOMDocument代表你的HTML文档:

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

谢谢!正是我在找什么。 –

+0

@尼克希尔莫汉:对不起,改了一下。您必须实际查询附加到文档的DOMXPath,而不是文档本身。 – cHao

+0

没关系。我已经修复了你的第一篇文章:) 还有一件事,如何找到没有img标签作为子元素的锚标签(而不是'src'和'alt',我需要锚文本)? –

使用简单的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; 

} 
+0

“src”和“alt”属性位于链接内的图像上。 – cHao

假设你的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通过针对具有href属性中的所有<a>标记的文档进行搜索。然后它会在每个发现的<a>标签下搜索以找到具有srcalt标签的任何<img>标签。然后它只抓取需要的属性并将它们添加到数组中。