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

使用json_encode生成JSON出现奇怪字符问题求助

解决JSON文件出现奇怪字符的问题

问题分析

你遇到的奇怪字符主要来自两个核心原因:

  1. 输入的HTML字符串处于HTML实体编码状态(比如<、"),DOMDocument加载后未正确解析这些实体,导致文本残留异常转义内容;
  2. 遍历DOM节点时捕获到大量含冗余空白(换行、制表符、连续空格)的文本节点,这些空白被JSON编码后显示为奇怪的转义字符或无效空白。

解决方案

1. 先解码HTML实体

将输入的实体编码HTML转换为真实HTML内容,再交给DOMDocument处理:

$htmlString = htmlspecialchars_decode($htmlString);

2. 强制DOMDocument使用UTF-8编码加载

避免编码不匹配导致的字符乱码问题:

$dom = new \DOMDocument();
libxml_use_internal_errors(true);
// 加入UTF-8声明,确保DOM解析编码一致
$dom->loadHTML('<?xml encoding="UTF-8">' . $htmlString);

3. 清理文本节点的冗余空白

过滤纯空白节点,同时将文本中的连续空白(换行、制表符等)压缩为单个空格:

foreach ($section->childNodes as $childNode)
{ 
    // 清理冗余空白:trim去除首尾空白,正则替换连续空白为单个空格
    $nodeValue = trim(preg_replace('/\s+/', ' ', $childNode->nodeValue)); 

    if (empty($nodeValue))
    {
        continue; 
    }

    $count++;
    $key = $keyPattern.'Text'.$count;
    $newArray[$key] = $nodeValue;
}

4. 优化JSON编码(可选)

若仍有特殊字符问题,补充JSON_UNESCAPED_SLASHES参数避免斜杠被转义:

Storage::disk('public')->put(
    $fileName, 
    json_encode($newArray, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)
);

修改后的完整代码

$htmlString = '&lt;section&gt;
        &lt;h2&gt;CCPA Privacy Notice Addendum&lt;/h2&gt;
        &lt;p&gt;This California Consumer Privacy Act (CCPA) Privacy Notice Addendum supplements the information provided in the [App Name] Privacy Policy and applies solely to residents of the State of California (&quot;consumers&quot; or &quot;you&quot;). We adopt this addendum to comply with the CCPA and provide you with the required information about your rights under the CCPA.&lt;/p&gt;
    &lt;/section&gt;';

// 解码HTML实体
$htmlString = htmlspecialchars_decode($htmlString);
        
$dom = new \DOMDocument();
libxml_use_internal_errors(true);
// 指定UTF-8编码加载HTML
$dom->loadHTML('<?xml encoding="UTF-8">' . $htmlString);

$count = 0;
$keyPattern = 'ccpaRights';
$newArray = [];

foreach ($dom->getElementsByTagName('section') as $section)
{
    foreach ($section->childNodes as $childNode)
    { 
        $nodeValue = trim(preg_replace('/\s+/', ' ', $childNode->nodeValue)); 

        if (empty($nodeValue))
        {
            continue; 
        }

        $count++;
        $key = $keyPattern.'Text'.$count;
        $newArray[$key] = $nodeValue;
    }
}

$fileName = '/temp/translated-'.rand(1,1000).'.json';
Storage::disk('public')->put(
    $fileName, 
    json_encode($newArray, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 06:10:35