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

时间:2016-08-31 07:00:38

标签: php xml symfony namespaces simplexml

对于谷歌站点地图,我想创建带有命名空间的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);

1 个答案:

答案 0 :(得分:1)

您需要在addChild调用中将命名空间指定为全局唯一的“命名空间标识符”(URI),而不是“本地前缀”。因此,在这种情况下,您将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时查找已为此命名空间指定的前缀,并提供所需的结果。