使用命名空间创建 SimpleXMLElement 节点并防止命名空间重复

Create SimpleXMLElement Node with Namespace and prevent namespace repeating

对于 google 站点地图,我想创建具有命名空间的 XML 节点。如何防止 simplexml 在每个节点上插入命名空间。

我需要的结构:

<xhtml:link 
             rel="alternate"
             hreflang="de"
             href="http://www.example.com/deutsch/"
             />

我的代码结构:

    <?xml version="1.0" encoding="UTF-8"?>
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
       <url>
          <loc>www.url.ch</loc>
          <xhtml:link xmlns:xhtml="xhtml" rel="alternate" hreflang="de-CH" href="www.url.ch/de">www.url.ch/de</xhtml:link>
          <xhtml:link xmlns:xhtml="xhtml" rel="alternate" hreflang="fr-CH" href="www.url.ch/fr">www.url.ch/fr</xhtml:link>
       </url>
    </urlset>

我的代码:

        $rootNode = new SimpleXMLElement(
            '<?xml version="1.0" encoding="utf-8"?>' .
            '   <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"></urlset>'
        );

        $urlNode = $rootNode->addChild('url');
        $urlNode->addChild('loc', 'www.url.ch');

        foreach (['de', 'fr', 'it', 'en'] as $locale) {
            if (in_array($locale, ['it', 'en'])) {
                continue;
            }

            $localeNode = $urlNode->addChild(
                'xhtml:link',
                'www.url.ch' . '/' . $locale,
                'xhtml'
            );

            $localeNode->addAttribute('rel', 'alternate');
            $localeNode->addAttribute('hreflang', $locale . '-CH');
            $localeNode->addAttribute('href', 'www.url.ch' . '/' . $locale);
        }

        $rootNode->saveXML($filePath);

您需要在 addChild 调用中将命名空间指定为全局唯一的 "namespace identifier" (URI) 而不是 "local prefix"。因此,在这种情况下,您将 xhtml 前缀绑定为 xmlns:xhtml="http://www.w3.org/1999/xhtml",因此名称空间 URI 为 http://www.w3.org/1999/xhtml:

$localeNode = $urlNode->addChild(
    'xhtml:link',
    'www.url.ch' . '/' . $locale,
    'http://www.w3.org/1999/xhtml'
);

XML 库然后在生成 XML 时查找已为此命名空间分配的前缀,并给出所需的结果。