如何实现XML feed新增条目时邮件或Slack通知?
入门指导:监控XML Feed并发送通知
第一步:验证并解析XML Feed
先确认XML格式是否有效,Zapier报错大概率是格式问题。用你熟悉的PHP写个简单测试脚本,快速验证解析可行性:
<?php $feedUrl = 'https://www.semtrack.de/e?i=251918536fedf0b20164555a698a7a0afd0c6dfd'; // 获取Feed内容 $xmlContent = file_get_contents($feedUrl); if (!$xmlContent) { die('无法获取Feed内容'); } // 开启错误捕获,避免解析失败直接崩溃 libxml_use_internal_errors(true); $xml = simplexml_load_string($xmlContent); if (!$xml) { echo 'XML解析错误:'; foreach(libxml_get_errors() as $error) { echo "\n" . $error->message; } libxml_clear_errors(); exit; } // 解析成功,打印第一条条目结构,方便后续字段调用 print_r($xml->entry[0]); // 若条目标签不是<entry>,替换成实际标签名(比如<item>) ?>
执行脚本后,若有错误根据提示调整(比如编码、标签嵌套问题);若成功,就能明确条目的字段结构(比如标题、唯一ID、发布时间等)。
第二步:记录已处理的条目
要识别新增内容,得把已处理过的条目ID存起来,用文本文件就能实现,无需复杂数据库:
<?php // 存储已处理条目ID的文件路径 $processedIdsFile = 'processed_ids.txt'; // 读取已处理ID列表 function getProcessedIds() { global $processedIdsFile; return file_exists($processedIdsFile) ? explode("\n", trim(file_get_contents($processedIdsFile))) : []; } // 新增已处理ID到文件 function addProcessedId($id) { global $processedIdsFile; file_put_contents($processedIdsFile, $id . "\n", FILE_APPEND); } ?>
第三步:对比条目,识别新增内容
结合前两步的代码,遍历XML条目,对比已处理ID,筛选出新增内容:
<?php $processedIds = getProcessedIds(); // 遍历所有条目,标签名根据实际XML结构调整 foreach ($xml->entry as $entry) { $entryId = (string)$entry->id; // 替换成条目里的唯一标识字段 if (!in_array($entryId, $processedIds)) { // 触发通知逻辑 sendNotification($entry); // 标记为已处理 addProcessedId($entryId); } } ?>
第四步:实现通知功能
发送邮件(用PHP内置函数)
<?php function sendNotification($entry) { $to = '你的邮箱地址'; $subject = 'XML Feed新增条目通知'; $message = "新增条目信息:\n标题:" . (string)$entry->title . "\n链接:" . (string)$entry->link['href']; // 字段名根据实际结构调整 $headers = 'From: noreply@example.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); } ?>
如果服务器禁用mail函数,可改用PHPMailer库(通过Composer安装),兼容性更强。
发送Slack通知
先在Slack后台创建Incoming Webhook,拿到专属URL后,用cURL发送请求:
<?php function sendNotification($entry) { $slackWebhookUrl = '你的Slack Webhook地址'; $msgData = [ 'text' => "⚠️ XML Feed新增条目\n*标题*: " . (string)$entry->title . "\n*链接*: " . (string)$entry->link['href'] ]; $ch = curl_init($slackWebhookUrl); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($msgData)); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); curl_exec($ch); curl_close($ch); } ?>
第五步:定时运行脚本
用系统定时任务定期执行脚本,实现持续监控:
- Linux系统:打开终端输入
crontab -e,添加一行(每5分钟执行一次,可按需调整):*/5 * * * * php /你的脚本完整路径/feed-monitor.php - Windows系统:打开「任务计划程序」,创建基本任务,设置触发器为每隔指定时间,操作选择启动
php.exe,参数填脚本路径。
注意事项
- 确保PHP环境允许访问外部URL(开启
allow_url_fopen,或用cURL替代file_get_contents) - 若XML编码异常,可通过
mb_convert_encoding转码后再解析 - 定期清理
processed_ids.txt,避免文件体积过大
内容的提问来源于stack exchange,提问作者ferdman
相关产品推荐
相关产品推荐

