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

SimpleXMLElement addAttribute丢失xmlns:前缀问题求助

解决SimpleXMLElement生成Google News站点地图时xmlns前缀丢失问题

问题原因

你遇到的情况是因为SimpleXMLElement对带冒号的属性处理逻辑特殊:xmlns:news这类命名空间声明属性,属于http://www.w3.org/2000/xmlns/这个特殊命名空间,直接用addAttribute('xmlns:news', ...)会被解析为普通的前缀属性,导致xmlns:被截断。

解决方案

方案1:创建根元素时直接声明所有命名空间

最直接的方式是在初始化SimpleXMLElement时,把需要的命名空间直接写在根元素里:

$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="https://www.google.com/schemas/sitemap-news/0.9"/>');

这样生成的XML会直接包含完整的命名空间声明,无需后续额外操作。

方案2:用addAttribute的第三个参数指定xmlns命名空间

如果必须动态添加命名空间,调用addAttribute时需要显式指定属性所属的xmlns命名空间URI:

$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><urlset/>');
$xml->addAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
// 第三个参数传入xmlns的标准命名空间URI
$xml->addAttribute('news', 'https://www.google.com/schemas/sitemap-news/0.9', 'http://www.w3.org/2000/xmlns/');

执行后生成的XML会正确显示xmlns:news="https://www.google.com/schemas/sitemap-news/0.9"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 06:50:27