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

如何程序化编辑script元素中的JSON-LD?批量更新HTML文件方案

用PHP或JavaScript批量更新HTML中的JSON-LD datePosted属性

嘿,既然你熟悉PHP,那咱先从PHP的实现方案入手,毕竟你有处理HTML文件的经验,上手肯定快!

PHP 实现步骤

1. 遍历目标目录下的HTML文件

首先得把所有要处理的HTML文件找出来,用glob()函数就能轻松搞定;要是需要递归遍历子目录,就用RecursiveDirectoryIterator搭配RecursiveIteratorIterator组合使用。

2. 提取并修改JSON-LD

核心思路是:读取HTML内容 → 匹配出JSON-LD脚本 → 解析成PHP数组 → 修改datePosted → 转回JSON → 替换回HTML → 保存文件。

这里给你写个完整的示例代码,带详细注释:

<?php
// 目标目录,改成你的HTML文件所在路径
$targetDir = './your-html-files/';
// 当前日期,格式和示例一致:YYYY-MM-DD
$currentDate = date('Y-m-d');

// 遍历目录下的所有HTML文件
$htmlFiles = glob($targetDir . '*.html');

foreach ($htmlFiles as $file) {
    // 读取文件内容
    $content = file_get_contents($file);
    if (!$content) {
        echo "无法读取文件:$file" . PHP_EOL;
        continue;
    }

    // 匹配JSON-LD脚本(兼容多行格式)
    $pattern = '/<script type="application\/ld\+json">(.*?)<\/script>/s';
    if (preg_match($pattern, $content, $matches)) {
        $jsonLdStr = $matches[1];
        // 解析JSON为PHP数组
        $jsonLd = json_decode(trim($jsonLdStr), true);
        
        // 可选:检查是否是JobPosting类型且存在datePosted属性
        if (isset($jsonLd['@type']) && $jsonLd['@type'] === 'JobPosting' && isset($jsonLd['datePosted'])) {
            // 更新datePosted为当前日期
            $jsonLd['datePosted'] = $currentDate;
            // 转回JSON,保持格式美观
            $newJsonLdStr = json_encode($jsonLd, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
            // 替换原来的JSON-LD内容
            $newContent = preg_replace($pattern, "<script type=\"application/ld+json\">$newJsonLdStr</script>", $content);
            // 保存修改后的文件
            if (file_put_contents($file, $newContent)) {
                echo "成功更新文件:$file" . PHP_EOL;
            } else {
                echo "保存文件失败:$file" . PHP_EOL;
            }
        } else {
            echo "文件$file中没有找到符合条件的datePosted属性" . PHP_EOL;
        }
    } else {
        echo "文件$file中没有找到JSON-LD脚本" . PHP_EOL;
    }
}
?>

注意事项

  • 先备份文件! 批量操作前一定要先测试单个文件,避免意外覆盖或损坏数据。
  • 如果遇到JSON-LD格式不规范的情况,json_decode可能失败,可以加错误判断:if (json_last_error() !== JSON_ERROR_NONE)来捕获解析问题。
  • 要是HTML里有多个JSON-LD脚本,把preg_match改成preg_match_all再循环处理即可。

JavaScript(Node.js)实现方案

要是你想试试Node.js的方式,也很简单,用fs模块处理文件,cheerio解析HTML(语法和jQuery类似,上手无压力):

1. 先安装依赖

npm install cheerio fs-extra

2. 示例代码

const fs = require('fs-extra');
const cheerio = require('cheerio');
const path = require('path');

// 目标目录
const targetDir = './your-html-files/';
// 当前日期,格式YYYY-MM-DD
const currentDate = new Date().toISOString().split('T')[0];

// 遍历目录处理文件
async function processFiles() {
    try {
        const files = await fs.readdir(targetDir);
        for (const file of files) {
            if (path.extname(file) === '.html') {
                const filePath = path.join(targetDir, file);
                const content = await fs.readFile(filePath, 'utf8');
                const $ = cheerio.load(content);
                
                // 找到所有JSON-LD脚本并处理
                $('script[type="application/ld+json"]').each((index, element) => {
                    const jsonLdStr = $(element).html().trim();
                    try {
                        const jsonLd = JSON.parse(jsonLdStr);
                        // 检查并更新datePosted
                        if (jsonLd['@type'] === 'JobPosting' && jsonLd.datePosted) {
                            jsonLd.datePosted = currentDate;
                            $(element).html(JSON.stringify(jsonLd, null, 2));
                        }
                    } catch (err) {
                        console.log(`解析${file}中的JSON-LD出错:`, err.message);
                    }
                });
                
                // 保存修改后的内容
                await fs.writeFile(filePath, $.html());
                console.log(`成功更新文件:${filePath}`);
            }
        }
    } catch (err) {
        console.error('处理出错:', err.message);
    }
}

processFiles();

推荐的JSON-LD解析器

如果觉得正则或简单JSON解析不够可靠(比如JSON-LD带复杂上下文、扩展结构),可以用专门的库:

  • PHP:可以用jsonld包,通过Composer安装,它能严格处理JSON-LD的上下文、类型扩展等特性,适合复杂场景。
  • JavaScript:jsonld.js库,专门用于JSON-LD的解析、转换和规范校验,支持各种标准特性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:20:49