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

标签 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);

最佳答案

您需要在 addChild 调用中将命名空间指定为全局唯一的“命名空间标识符”(URI),而不是“本地前缀”。所以在这种情况下,您将 xhtml 前缀绑定(bind)为 xmlns:xhtml="http://www.w3.org/1999/xhtml" 所以 namespace URI 是http://www.w3.org/1999/xhtml:

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

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

关于php - 使用命名空间创建 SimpleXMLElement 节点并防止命名空间重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39242790/

相关文章:

php - PDO:prepare() 是否会转义所有数据,即使未绑定(bind)?

php - 如何删除 Dotdeb 版本的 PHP 并将其替换为官方 Ubuntu 存储库

php - XAMPP 7.0.23 上的 SSL 错误 : SEC_ERROR_UNKNOWN_ISSUER

java - 如何将解析和更改的 DOM 文档保存在 xml 文件中?

xml - 使用 XSLT 将 KML 拆分为子文件,几乎在那里,但无法使其工作

c++ - 桌面应用程序数据库

symfony - Sylius + Vagrant + Behat 不工作

symfony - Doctrine/Symfony : convert custom type to database value before using QueryBuilder

php - wamp 本地主机 SSL 错误上的 Amazon S3

php - 没有 SSH 访问权限的 Symfony 2