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

PHP代码中移除%0D字符解决RSS摘要邮件simplexml_load_file报错

问题描述

开发每日RSS订阅摘要邮件的PHP程序时,运行时报错:

simplexml_load_file(https://hdblog.it/feed%0D): failed to open stream: Invalid redirect URL!

错误根源是URL里多了%0D字符(回车符),需要修改代码移除该字符。相关代码如下:

// Set the timezone to Rome, Italy
date_default_timezone_set('Europe/Rome');

// Set the cutoff time to 24 hours ago
$cutoff_time = time() - (24 * 60 * 60);

// Set the subject of the email
$subject = "Digest RSS " . date("d/m/Y");

// Initialize the message
$message = "<html><body>";
$message .= "<h1>RSS Digest</h1>";
$message .= "<p>Ecco gli ultimi aggiornamenti dai tuoi feed RSS:</p>";

// Read the list of RSS feeds from a file
$rss_feeds_file = file_get_contents('rss_feeds.txt');
$rss_feeds = explode("\n", $rss_feeds_file);

// Loop through the list of RSS feeds
foreach ($rss_feeds as $rss_feed) {
  // Load the RSS feed
  $rss = simplexml_load_file($rss_feed);
  if ($rss) {
    // Initialize a flag to keep track of whether there are feed items to include in the email
    $items_included = false;

    // Add the feed title to the message
    $message .= "<h2>" . $rss->channel->title . "</h2>";
    // Add a list of items to the message
    $message .= "<ul>";

    // Loop through the feed items
    foreach($rss->channel->item as $item) {
      // Check if the item was published within the last 24 hours
      $item_time = strtotime($item->pubDate);
      if ($item_time > $cutoff_time) {
        // If it was, add the feed item to the email
        $message .= "<li><a href='" . $item->link . "'>" . $item->title . "</a><br />";
        $message .= strip_tags($item->description) . "</li>";
        $items_included = true;
      }
    }
    $message .= "</ul>";
  }
}

$message .= "</body></html>";
解决方案

问题出在从rss_feeds.txt读取链接时,每行末尾的回车/换行符被保留到了URL里,最终被URL编码成%0D。直接在遍历每个RSS链接时清理掉两端空白字符即可,同时还能跳过空行:

修改遍历部分的代码:

// Loop through the list of RSS feeds
foreach ($rss_feeds as $rss_feed) {
  // 清理URL两端的回车、换行、空格等空白字符
  $clean_rss_feed = trim($rss_feed);
  // 跳过空行,避免无效请求
  if(empty($clean_rss_feed)) continue;
  
  // Load the RSS feed
  $rss = simplexml_load_file($clean_rss_feed);
  // 后续代码保持不变...
}

另外,如果要更彻底处理不同操作系统的换行格式(比如Windows的\r\n、Linux的\n、旧Mac的\r),可以把分割链接的代码改成用正则匹配所有换行格式:

// Read the list of RSS feeds from a file
$rss_feeds_file = file_get_contents('rss_feeds.txt');
// 兼容所有换行格式分割链接
$rss_feeds = preg_split('/\r\n|\r|\n/', $rss_feeds_file);

这样能从根源避免换行符残留的问题,再配合trim处理双保险,就不会再出现URL里带%0D的情况了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 07:55:41