php - 使用 php dom 生成 xml 命名空间

标签 php xml dom namespaces

这个问题在这里已经有了答案:





How to declare an XML namespace prefix with DOM/PHP?

(1 个回答)


8 年前关闭。




我对 XML、命名空间和 PHP DOM 有一些问题。

这是我应该得到的输出:

<cd:Document xmlns="http://www.zbs-giz.si/Schemas/2006/ZBSxml/2.2" xmlns:cd="http://www.crea.si/Schemas/2004/Document/ZBSxml/2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.crea.si/Schemas/2004/Document/ZBSxml/2.0/ZbsCreaDoc.xsd">
<cd:Data>
    <cd:DataFormat>
        <cd:MimeType>text/xml</cd:MimeType>
    </cd:DataFormat>
    <cd:Content>
        <cd:EmbeddedData>

这是我的 PHP 代码
$root = $doc->appendChild($doc->createElementNS('http://www.zbs-giz.si/Schemas/2006/ZBSxml/2.2', 'cd:Document'));
$root->setAttributeNS('http://www.zbs-giz.si/Schemas/2006/ZBSxml/2.2', 'cd', 'http://www.crea.si/Schemas/2004/Document/ZBSxml/2.0');
$root->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi:schemaLocation', 'http://www.crea.si/Schemas/2004/Document/ZBSxml/2.0/ZbsCreaDoc.xsd');

任何想法如何解决这个问题?

最佳答案

<?php
$doc = new DOMDocument();
$doc->formatOutput = true;
//set root element to correct cd prefix _and_ namespace:
$root = $doc->appendChild(
        $doc->createElementNS(
        $cd = 'http://www.crea.si/Schemas/2004/Document/ZBSxml/2.0',
        'cd:Document'));
//this is the bit of obscure magic: it will set the default namespace
$doc->createAttributeNS(
        'http://www.zbs-giz.si/Schemas/2006/ZBSxml/2.2',
        'xmlns');
//now continue as normal
$root->setAttributeNS(
        'http://www.w3.org/2001/XMLSchema-instance',
        'xsi:schemaLocation',
        'http://www.crea.si/Schemas/2004/Document/ZBSxml/2.0/ZbsCreaDoc.xsd');
$data = $root->appendChild($doc->createElementNS($cd,'cd:Data'));
$dataformat = $data->appendChild($doc->createElementNS($cd,'cd:DataFormat'));
$dataformat->appendChild($doc->createElementNS($cd,'cd:MimeType','text/xml'));
$content = $data->appendChild($doc->createElementNS($cd,'cd:Content'));

关于php - 使用 php dom 生成 xml 命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9082032/

相关文章:

php mysql 移动选定的标签

未找到 PHP 类

xml - Groovy - 使用单引号创建有效的 XML 文件是不可能的

javascript - JavaScript 中的模块模式

javascript - 使用 window.onscroll 事件检测页面/框架滚动

php - 按位运算符的 MySQL 状态交换

php - 未定义表 : 7 ERROR: relation "expenses" does not exist

java - Java 中的 SAX 解析问题

java - fragment 中的 super.onCreateView

javascript - 如何将所有 text_node nodeValue 的一部分包装在 html 元素中?