博客sitemap.xml不更新求助(附sitemap.php代码及Cron Jobs配置)
问题
我给博客配置了自动生成站点地图的sitemap.php,最初发布2篇文章时,sitemap.xml成功生成对应条目;但新增2篇文章后,sitemap.xml不再更新。我已设置每15分钟执行一次的Cron Jobs来触发sitemap.php,代码如下:
<?php include 'db.php'; $sqlSitemap = "SELECT * FROM articles"; $resultSitemap = $conn->query($sqlSitemap); // Start building the XML $xml = '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL; $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL; // Loop through articles and add them to the XML while ($rowSitemap = $resultSitemap->fetch_assoc()) { $url = 'https://bilimevreni.com/makale?id=' . $rowSitemap['id']; $xml .= '<url>' . PHP_EOL; $xml .= '<loc>' . htmlspecialchars($url) . '</loc>' . PHP_EOL; $xml .= '<lastmod>' . date('c') . '</lastmod>' . PHP_EOL; $xml .= '<changefreq>daily</changefreq>' . PHP_EOL; $xml .= '</url>' . PHP_EOL; } // Close the XML $xml .= '</urlset>'; // Save the XML to sitemap.xml file_put_contents('sitemap.xml', $xml); $conn->close(); ?>
解决方案
验证数据库查询结果
在$resultSitemap = $conn->query($sqlSitemap);后添加调试代码:var_dump($resultSitemap->num_rows);,然后手动执行脚本(服务器终端运行php sitemap.php),查看输出的条目数是否为4。如果不是,排查:db.php中的数据库连接参数在Cron环境下是否有效(部分服务器需指定socket路径而非localhost)articles表中是否确实存在新增的2篇文章
排查Cron Jobs的执行问题
Cron执行环境与网页环境存在差异,需确认:- Cron命令使用了正确的PHP绝对路径,例如:
*/15 * * * * /usr/bin/php /home/your-site/public_html/sitemap.php(替换为你服务器的PHP路径和脚本绝对路径) - 执行Cron的用户拥有写入
sitemap.xml的权限,可在代码中添加日志记录:error_log('Sitemap generated: ' . $resultSitemap->num_rows . ' entries');,然后查看服务器错误日志确认脚本是否被执行
- Cron命令使用了正确的PHP绝对路径,例如:
修正文件写入的路径问题
file_put_contents('sitemap.xml', $xml);使用相对路径,Cron执行时的工作目录可能不是脚本所在目录,导致文件写入错误位置。改为绝对路径,例如:file_put_contents('/home/your-site/public_html/sitemap.xml', $xml);优化
lastmod字段逻辑
当前代码中lastmod使用的是生成站点地图的时间,不符合规范,应改为使用文章自身的更新时间。假设articles表有updated_at字段,修改代码为:$xml .= '<lastmod>' . date('c', strtotime($rowSitemap['updated_at'])) . '</lastmod>' . PHP_EOL;
内容的提问来源于stack exchange,提问作者Lcaro
相关产品推荐
相关产品推荐

