php - 使用 PHP Simple HTML DOM Parser 从 html 中提取 dom 元素

标签 php html dom simple-html-dom

我正在尝试从 this site 中提取文章(包括文本)的链接。使用PHP Simple HTML DOM PARSER .

enter image description here

我想提取主页中文章的所有 h2 标签,我正在尝试这样做:

    $html = file_get_html('http://www.winbeta.org');
    $articles = $html->getElementsByTagName('article');
    $a = null;

    foreach ($articles->find('h2') as $header) {
                $a[] = $header;
    }

    print_r($a);

根据手册,它应该首先获取article标签内的所有内容,然后为每篇文章提取h2并保存在数组中。但它给了我:

enter image description here

编辑 enter image description here

最佳答案

有几个问题:

  • getElementsByTagName 显然返回一个节点,而不是一个数组,因此如果页面上有多个 article 标记,它就不起作用。而是使用 find 来返回一个数组;
  • 但是一旦进行了该切换,您就无法对 find 的结果使用 find,因此您应该对每篇匹配的文章执行此操作。 > 标签,或者最好使用组合选择器作为 find 的参数;
  • 主要问题:您必须使用 ->plaintext 显式检索节点的文本内容,否则您将获得节点的对象表示形式,及其所有属性和内部结构;
  • 某些文本包含 HTML 实体,例如 。这些可以使用 html_entity_decode 进行解码。

所以这段代码应该可以工作:

$a = array();
foreach ($html->find('article h2') as $h2) { // any h2 within article
    $a[] = html_entity_decode($h2->plaintext);
}

使用array_map,你也可以这样做:

$a = array_map(function ($h2) { return html_entity_decode($h2->plaintext); }, 
               $html->find('article h2'));

如果您还需要检索文章中的其他标签,将其文本存储在不同的数组中,那么您可以执行以下操作:

$a = array();
$b = array();
foreach ($html->find('article') as $article) {
    foreach ($article->find('h2') as $h2) {
        $a[] = html_entity_decode($h2->plaintext);
    }
    foreach ($article->find('h3') as $h3) {
        $b[] = html_entity_decode($h3->plaintext);
    }
}

关于php - 使用 PHP Simple HTML DOM Parser 从 html 中提取 dom 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34620043/

相关文章:

php - yii 框架填充 textarea 中的值

javascript - 在 Javascript 中解析来自 PHP 的编码数据

javascript - 当用户使用移动网络时 GeoIP 是否工作

html - ie8 打破 float :left into 2 rows

Javascript - 用现有按钮替换输入类型按钮

java - 如何使用 DOM 解析器解析以下 xml?

php - 如何在mysql中使用存储在unix_timestamp中的日期进行提醒

javascript - IE8 未在输入时运行搜索字段并跳闸 javascript 验证

JavaScript 坏了?

javascript - 导出 DOM 的当前样式