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

SimpleXMLElement命名空间错误:xhtml前缀未定义的问题与解决

解决SimpleXMLElement创建时的命名空间前缀未定义错误

问题场景

获取gzip压缩的站点地图数据,解码后使用SimpleXMLElement解析时触发如下错误:

Warning: SimpleXMLElement::__construct(): namespace error : Namespace prefix xhtml on link is not defined in

相关PHP代码

$urlget = $curl->getPage($url);    
$gz = gzdecode($urlget);    
$d2 = new SimpleXMLElement($gz);

站点地图XML结构

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
<url>
    <loc></loc>
    <xhtml:link rel="alternate" hreflang="es-ad" href="" />
</url>
<url>
    <loc></loc>
    <image:image> 
    <image:loc></image:loc>
    <image:title></image:title>
    <image:caption></image:caption>
    </image:image>
</url>

解决方案

错误原因是XML中使用了xhtml:前缀,但未在根节点声明对应的命名空间。需要站点地图提供者在<urlset>标签中添加xhtml命名空间定义:

修改后的<urlset>标签:

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" 
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
        xmlns:xhtml="http://www.w3.org/1999/xhtml">

添加命名空间声明后,XML即可被SimpleXMLElement正常解析,错误消除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 05:24:12