doukuiqian9911 2016-08-31 07:00
浏览 96
已采纳

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

For a google sitemap I want to create XML nodes with namespace. How can I prevent simplexml from inserting the namespace on each node.

Structure that I need:

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

Structure from my code:

    <?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>

My Code:

        $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条回答 默认 最新

  • douli2063 2016-08-31 09:29
    关注

    You need to specify the namespace in the addChild call as the globally unique "namespace identifier" (URI) not the "local prefix". So in this case, you are binding the xhtml prefix as xmlns:xhtml="http://www.w3.org/1999/xhtml" so the namespace URI is http://www.w3.org/1999/xhtml:

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

    The XML library then looks up the already-assigned prefix for this namespace when generating the XML, and gives the desired result.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比