在PHP中从HTML中提取所有text和img标签。

时间:2011-11-05 16:32:04

标签: php html parsing

  

可能重复:
  Best methods to parse HTML with PHP

对于一个项目,我需要一个HTML页面并从中提取所有文本和img标签,并保持它们在网页中出现的顺序。

例如,如果网页是:

<p>Hi</p>
<a href ="test.com" alt="a link"> text link</a>
<img src="test.png" />
<a href ="test.com"><img src="test2.png" /></a>

我想以这种格式检索该信息:

text - Hi
Link1 - <a href ="test.com">text link</a>  notice without alt or other tag
Img1 - test.png  
Link2 - <a href ="test.com"><img src="test2.png" /></a>  again no tag

有没有办法在PHP中实现?

2 个答案:

答案 0 :(得分:1)

  

有没有办法在php中制作它?

是的,您可以首先删除您不感兴趣的所有标记,然后使用DOMDocument删除所有不需要的属性。最后,您需要重新运行strip_tags以删除DomDocument添加的标记:

$allowed_tags = '<a><img>';
$allowed_attributes = array('href', 'src');

$html = strip_tags($html, $allowed_tags);
$dom = new DOMDocument();

$dom->loadHTML($html);

foreach($dom->getElementsByTagName('*') as $node)
{
    foreach($node->attributes as $attribute)
    {
        if (in_array($attribute->name, $allowed_attributes)) continue;
        $node->removeAttributeNode($attribute);
    }
}

$html = $dom->saveHTML($dom->getElementsByTagname('body')->item(0));
$html = strip_tags($html, $allowed_tags);

Demo

答案 1 :(得分:-1)

我会使用 HTML Parser 将信息从网站中提取出来。阅读。

相关问题