【问题标题】:php: Extract text between specific tags from a webpage [duplicate]php:从网页中提取特定标签之间的文本[重复]
【发布时间】:2011-12-03 16:29:47
【问题描述】:

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

我知道我应该使用像 php domdocument (http://docs.php.net/manual/en/domdocument.loadhtml.php) 或 tagoup 这样的 html 解析器。

如何使用 php domdocument 提取特定标签之间的文本,例如获取 h1、h2、h3、p、table 之间的文本?看来我只能使用 getelementbytagname 对一个标签执行此操作。

是否有更好的 html 解析器来完成此类任务?或者我将如何遍历 php domdocument?

【问题讨论】:

    标签: php regex html-parsing


    【解决方案1】:

    您可以使用正则表达式来做到这一点。

    preg_match_all('#<h1>([^<]*)</h1>#Usi', $html_string, $matches);
    foreach ($matches as $match)
    {
      // do something with $match
    }
    

    【讨论】:

    • 请不要为此使用正则表达式!众所周知,正则表达式在解析 HTML 时不可靠。
    【解决方案2】:

    你是对的,使用 DomDocument(因为正则表达式不是解析 HTML 的好主意。为什么?请参阅 herehere 了解原因)。

    getElementsByTagName 为您提供DOMNodeList,您可以对其进行迭代以获取所有找到的元素的文本。因此,您的代码可能类似于:

    $document = new \DOMDocument();
    $document->loadHTML($html);
    
    $tags = array ('h1', 'h2', 'h3', 'h4', 'p');
    $texts = array ();
    foreach($tags as $tag)
    {
      $elementList = $document->getElementsByTagName($tag);
      foreach($elementList as $element)
      {
         $texts[$element->tagName][] = $element->textContent;
      }
    }
    return $texts;
    

    请注意,您可能应该在其中进行一些错误处理,并且您还会丢失文本的上下文,但您可以根据需要编辑此代码。

    【讨论】:

    • 谢谢,看起来不错。在一些网页上尝试过,比如 yahoo.com(刚刚添加了 $html = file_get_contents("http://yahoo.com");,但它总是失败并给出可怕的 domdocument.loadhtml&lt;/a&gt;]: htmlParseEntityRef: expecting ';' in Entity 我想必须检查 tagoup 或 simplehtmldom。:) 虽然算法看起来不错。跨度>
    【解决方案3】:

    我不确定您的来源是什么,所以我添加了一个通过 URL 获取内容的功能。

    $file = file_get_contents($url);
    
    $doc = new DOMDocument();
    $doc->loadHTML($file);
    
    $body = $doc->getElementsByTagName('body');
    $h1 = $body->getElementsByTagName('h1');
    

    我不确定这部分:

    for ($i = 0; $i < $items->length; $i++) {
        echo $items->item($i)->nodeValue . "\n";
    }
    

    或者:

    foreach ($items as $item) {
        echo $item->nodeValue . "\n";
    }
    

    这里是关于 nodeValue 的更多信息:http://docs.php.net/manual/en/function.domnode-node-value.php

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-19
      • 2012-07-19
      • 1970-01-01
      • 2012-06-28
      • 2011-11-19
      • 2019-09-04
      • 2018-01-27
      • 1970-01-01
      相关资源
      最近更新 更多