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

使用DOMDocument生成sitemap时输出丢失AttributeNode属性如何解决

解决方法

第一步:先确认属性是否真的未写入

你看到的无属性的XML内容大概率是浏览器的XML预览界面的展示效果,浏览器解析XML时会默认隐藏命名空间类属性,你右键点击页面选择「查看网页源代码」,就能看到完整的文件内容,很多时候属性已经正确生成,只是预览界面没有展示。
如果确认源代码中urlset标签确实没有添加的属性,再按下面的步骤修改代码。

第二步:修改属性添加逻辑

PHP的DOM扩展对xmlns:开头的命名空间声明属性有特殊处理规则,使用DOMAttr + setAttributeNode()的方式添加的命名空间属性不会被识别为合法声明,会被自动过滤,直接使用setAttribute()方法添加即可。
同时标准sitemap协议还需要补充默认的sitemap命名空间,修改后的完整代码如下:

$dom = new \DOMDocument();
$dom->encoding = 'utf-8';
$dom->xmlVersion = '1.0';
$dom->formatOutput = true;
$xml_file_name = './sitemap.xml';
$urlset = $dom->createElement('urlset');

// 改用setAttribute添加命名空间属性
$urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
$urlset->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
$urlset->setAttribute('xsi:schemaLocation', 'http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd');

$url_node = $dom->createElement('url');

$url_node_loc = $dom->createElement('loc',   'http://localhost' );
$url_node->appendChild($url_node_loc);

$url_node_lastmod = $dom->createElement('lastmod',  '2021-08-03T22:17:47+04:30' );
$url_node->appendChild($url_node_lastmod);

$urlset->appendChild($url_node);

$dom->appendChild($urlset);
$dom->save($xml_file_name);
dd('done');

修改后生成的XML文件(查看源代码)会显示正确的urlset属性:

<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
  <url>
    <loc>http://localhost</loc>
    <lastmod>2021-08-03T22:17:47+04:30</lastmod>
  </url>
</urlset>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:06:05