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

使用PHP Simple HTML DOM Parser提取指定区间内ft04类p标签的公司名文本

使用PHP Simple HTML DOM Parser提取指定段落内容

我来给你一步步拆解怎么用PHP Simple HTML DOM Parser完成这两个需求,代码都是可直接复用的哦~

1. 基础需求:查找带特定类的<p>标签并提取内容

首先得确保你已经引入了PHP Simple HTML DOM Parser的库文件,接下来用这段代码就能快速提取目标内容:

// 引入Simple HTML DOM Parser库
include('simple_html_dom.php');

// 你的HTML片段(也可以从文件或URL加载,用file_get_html()即可)
$htmlContent = '<p class = "ft00">Introduction</p> <p class = "ft00">John Smith</p> <p class = "ft02">Email:</p> <p class = "ft02">Phone Number:</p> <p class = "ft00">John@gmail.com</p> <p class = "ft00">Work Experience</p> <p class = "ft00">27 July 2017</p> <p class="ft04">ABC Tech Solutions - Senior Developer</p> <p class="ft04">XYZ Corp - Software Engineer</p> <p class = "ft00">EDUCATION AND TRAINING</p>';

// 加载HTML内容
$dom = str_get_html($htmlContent);

// 精准定位所有class为ft04的p标签
$targetParagraphs = $dom->find('p.ft04');

// 遍历提取纯文本内容
foreach ($targetParagraphs as $paragraph) {
    echo trim($paragraph->plaintext) . PHP_EOL;
}

// 记得清理DOM资源,避免内存泄漏
$dom->clear();

这段代码的核心是find('p.ft04'),它会帮你筛选出所有带有ft04类的段落标签,再用plaintext获取标签里的纯文本内容,非常直观。

2. 进阶需求:提取“Work Experience”与“EDUCATION AND TRAINING”之间的ft04类p标签内容

这个需求需要先定位两个标题的位置,再在区间内筛选目标标签,逻辑稍微绕一点,但很好理解:

include('simple_html_dom.php');

$htmlContent = '<p class = "ft00">Introduction</p> <p class = "ft00">John Smith</p> <p class = "ft02">Email:</p> <p class = "ft02">Phone Number:</p> <p class = "ft00">John@gmail.com</p> <p class = "ft00">Work Experience</p> <p class = "ft00">27 July 2017</p> <p class="ft04">ABC Tech Solutions - Senior Developer</p> <p class="ft04">XYZ Corp - Software Engineer</p> <p class = "ft00">EDUCATION AND TRAINING</p>';

$dom = str_get_html($htmlContent);

$isInTargetRange = false;
$companyNames = [];

// 遍历所有p标签,逐个判断位置
foreach ($dom->find('p') as $paragraph) {
    $currentText = trim($paragraph->plaintext);
    
    // 找到"Work Experience"后,开启提取模式
    if ($currentText === 'Work Experience') {
        $isInTargetRange = true;
        continue;
    }
    
    // 找到"EDUCATION AND TRAINING"后,立刻停止遍历
    if ($currentText === 'EDUCATION AND TRAINING') {
        break;
    }
    
    // 处于目标区间内,且标签class是ft04,就提取公司名
    if ($isInTargetRange && $paragraph->class === 'ft04') {
        // 假设文本格式是"公司名 - 职位",分割取前半部分
        $companyName = explode(' - ', $currentText)[0];
        $companyNames[] = $companyName;
    }
}

// 输出提取到的公司名称
print_r($companyNames);

$dom->clear();

这里用了一个状态变量isInTargetRange来标记是否进入了“Work Experience”和“EDUCATION AND TRAINING”之间的区间,一旦进入就开始筛选class为ft04的段落,最后按你需要的格式提取公司名称(如果你的文本格式和示例不同,只需要调整explode的逻辑就行)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:54:27