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

PHP使用html2text提取HTML纯文本遇异常,求解决方案

解决PHP从HTML提取纯文本时变量丢失、文本大写的问题

我懂你碰到的糟心事——那个html2text库处理带变量的HTML时简直离谱,不仅把标题转成全大写,还把你的$account_name变量给吞了!别慌,咱们用PHP原生工具就能搞定,不用依赖第三方库,还更靠谱,完全满足你提取纯文本、将div/p/标题标签转为换行的需求。

方案1:用DOMDocument精准提取文本(推荐)

这个方法会遍历HTML节点,精准提取每个元素内的有效文本,完美保留变量和原文本格式,还能按标签自动添加换行:

$html = '<div class="mozaik-inner" style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:22.4px;color:rgb(68,68,68);padding:0px 30px;margin:0px auto;width:600px;background-color:rgb(250,250,250);"><h2 style="font-family:Arial, Helvetica, sans-serif;font-size:18px;line-height:28.8px;color:#444444;padding:0px;margin:0px;">Account Details for $account_name :</h2><p style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:22.4px;color:#444444;padding:0px;margin:0px;">TOID: $account_to_id_c</p><p style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:22.4px;color:#444444;padding:0px;margin:0px;"> </p></div>';

// 初始化DOMDocument,处理HTML格式问题避免警告
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();

// 获取body下的所有子节点
$textNodes = $dom->getElementsByTagName('body')->item(0)->childNodes;
$result = '';

foreach ($textNodes as $node) {
    // 只处理元素节点(div、h2、p等)
    if ($node->nodeType === XML_ELEMENT_NODE) {
        // 提取文本并去除多余空白
        $text = trim($node->textContent);
        if (!empty($text)) {
            $result .= $text . "\n"; // 每个标签内容后添加换行
        }
    }
}

// 去除末尾多余换行,输出结果
$result = trim($result);
echo $result;

执行后输出:

Account Details for $account_name :
TOID: $account_to_id_c

方案2:简单粗暴的strip_tags+正则处理(适合结构简单的HTML)

如果你的HTML结构不复杂,这个方法更快捷,先去掉所有标签,再整理空白和换行:

$html = '<div class="mozaik-inner" style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:22.4px;color:rgb(68,68,68);padding:0px 30px;margin:0px auto;width:600px;background-color:rgb(250,250,250);"><h2 style="font-family:Arial, Helvetica, sans-serif;font-size:18px;line-height:28.8px;color:#444444;padding:0px;margin:0px;">Account Details for $account_name :</h2><p style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:22.4px;color:#444444;padding:0px;margin:0px;">TOID: $account_to_id_c</p><p style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:22.4px;color:#444444;padding:0px;margin:0px;"> </p></div>';

// 先替换标题和段落标签为换行,确保结构分隔
$html = str_replace(['</h2>', '</p>'], ["\n", "\n"], $html);
// 去掉所有HTML标签
$rawText = strip_tags($html);
// 去除多余的空白和换行,保留有效分隔
$processedText = trim(preg_replace('/\s+/', ' ', $rawText));

echo $processedText;

这个方法也能完美保留你的变量,输出符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:28:26