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

如何将HTML文本转换为适配Facebook Graph API的富文本?

解决HTML转Facebook Graph API适配格式问题

核心方案:HTML节点解析+标签替换

Facebook Graph API支持粗体**、斜体*这类轻量Markdown格式,我们需要把数据库里的HTML标签转换为对应格式,同时移除<p>这类不必要的容器标签。HTMLPurifier的定位是HTML内容净化,而非格式转换,所以无法满足需求,直接用DOM解析的方式更精准。

PHP实现示例

function convertHtmlToFbCompatibleText($htmlContent) {
    // 初始化DOM解析器,忽略HTML语法错误
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML($htmlContent);
    libxml_clear_errors();

    $xpath = new DOMXPath($dom);
    $targetNodes = $xpath->query('//text() | //strong | //em');
    $output = '';

    foreach ($targetNodes as $node) {
        if ($node instanceof DOMElement) {
            $text = trim($node->nodeValue);
            if (empty($text)) continue;
            
            switch ($node->tagName) {
                case 'strong':
                    $output .= "**$text** ";
                    break;
                case 'em':
                    $output .= "*$text* ";
                    break;
            }
        } else {
            $text = trim($node->nodeValue);
            if (!empty($text)) {
                $output .= "$text ";
            }
        }
    }

    // 清理多余空格,确保格式整洁
    return trim(preg_replace('/\s+/', ' ', $output));
}

// 测试转换
$dbHtml = '<p>✨ <strong>Discover Elegance Redefined</strong>! Explore the brilliance of this meticulously crafted <em>platinum engagement ring</em>, featuring a stunning <strong>pavé diamond band</strong> that perfectly complements its breathtaking <strong>center stone</strong>. 💍 #ForeverBrilliant #EngagementRing #LuxuryJewelry #DiamondLove ✨</p>';
echo convertHtmlToFbCompatibleText($dbHtml);

转换逻辑说明

  1. 用DOM解析HTML内容,避开正则替换的局限性;
  2. 遍历目标节点(文本、<strong>、<em>),将<strong>替换为**内容**,<em>替换为*内容*;
  3. 自动清理多余空格,保留表情、话题标签等特殊内容;
  4. 自动过滤<p>这类外层容器标签,只保留有效内容。

JavaScript/Node.js适配思路

function convertHtmlToFbText(html) {
    const parser = new DOMParser();
    const doc = parser.parseFromString(html, 'text/html');
    let result = '';

    function traverse(node) {
        if (node.nodeType === Node.TEXT_NODE) {
            const text = node.textContent.trim();
            if (text) result += text + ' ';
        } else if (node.nodeType === Node.ELEMENT_NODE) {
            if (node.tagName === 'STRONG') {
                result += '**' + node.textContent.trim() + '** ';
            } else if (node.tagName === 'EM') {
                result += '*' + node.textContent.trim() + '* ';
            } else {
                // 遍历子节点处理其他容器标签
                node.childNodes.forEach(traverse);
            }
        }
    }

    traverse(doc.body);
    return result.trim().replace(/\s+/g, ' ');
}

内容的提问来源于stack exchange,提问作者Ahmed Alaa El-Din Hassan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 22:08:14