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

使用Simple HTML DOM Parser按指定th文本获取对应td的方法

实现代码
// 若加载本地HTML文件使用file_get_html,若传入HTML字符串则使用str_get_html
$html = file_get_html('table.html');
$table = $html->find('table', 0);
$targetTdContent = '';

// 遍历表格所有行
foreach ($table->find('tr') as $row) {
    $th = $row->find('th', 0);
    // 匹配th文本为test2的行
    if ($th && trim($th->plaintext) === 'test2') {
        // 提取对应td的文本内容
        $targetTdContent = trim($row->find('td', 0)->plaintext);
        break;
    }
}

// 输出结果:mydata2
echo $targetTdContent;
注意事项
  • Simple HTML DOM Parser 不支持你尝试的自定义跨节点条件选择器语法,需要手动遍历行匹配对应th的文本
  • 你原本的代码存在语法错误:str_get_html('table.html)'括号未闭合,且str_get_html仅支持传入HTML字符串,读取本地文件需要使用file_get_html方法
  • 表格中的th没有src属性,不要将节点文本匹配和元素属性选择器用法混淆,获取节点文本需使用plaintext属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:06:00