You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP关联H1标签与后续同级div标签内容构建父子关系

PHP 实现 H1 与对应 items 类 Div 的关联抓取

方法一:使用 Simple HTML Dom

核心思路是按文档顺序遍历所有目标元素(H1 和 class 为 items 的 div),遇到 H1 就创建新分组,后续的 items div 自动归到当前 H1 下,直到下一个 H1 出现。

require 'simple_html_dom.php';

// 加载网页内容(替换为你的目标页面或内容)
$html = file_get_contents('target-page.html');
$dom = str_get_html($html);

$output = [];
$currentTitle = null;

// 遍历所有H1和items类div
foreach ($dom->find('h1, div.items') as $elem) {
    if ($elem->tag === 'h1') {
        // 切换当前标题分组
        $currentTitle = trim($elem->plaintext);
        $output[$currentTitle] = [];
    } elseif ($currentTitle !== null && $elem->class === 'items') {
        // 将当前items div内容加入对应标题分组
        $output[$currentTitle][] = [
            'text' => trim($elem->plaintext),
            'html' => $elem->innertext // 若需要保留HTML结构可启用
        ];
    }
}

print_r($output);

方法二:使用 Goutte\Client

基于 Symfony DomCrawler,逻辑和上面一致,按文档顺序处理节点:

use Goutte\Client;

$client = new Client();
$crawler = $client->request('GET', 'target-page.html');

$output = [];
$currentTitle = null;

// 筛选并遍历目标节点
$crawler->filter('h1, div.items')->each(function ($node) use (&$currentTitle, &$output) {
    if ($node->nodeName() === 'h1') {
        $currentTitle = trim($node->text());
        $output[$currentTitle] = [];
    } elseif ($currentTitle !== null && $node->attr('class') === 'items') {
        $output[$currentTitle][] = [
            'text' => trim($node->text()),
            'html' => $node->html()
        ];
    }
});

print_r($output);

关键说明

  • 这种方式无需依赖兄弟节点判断,不管两个 H1 之间有多少其他无关元素,只会收集属于当前 H1 区间内的 items 类 div。
  • 若需更复杂的内容提取(比如 div 内的子元素),只需修改对应位置的节点处理逻辑即可。

内容的提问来源于stack exchange,提问作者Arcade

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 12:21:13