将前缀/命名空间添加到XML

时间:2017-02-28 13:40:43

标签: php xml domdocument

我生成了一个简单的xml。我想在xml中添加namespace /前缀是否有使用php DomDocument的方法。或者我是否需要使用核心php来替换标签并在xml中重新创建它。

pwd

预期输出

<?xml version="1.0" encoding="UTF-8"?>
<orderShipment>
    <orderData>
        <productId>1</productId>
        <orderStatus>
            <status>Shipped</status>
            <statusQuantity>
                <amount>1</amount>
            </statusQuantity>
            <trackingInfo>
                <shipDateTime>Fri, 24 Feb 2017</shipDateTime>
                <carrierName>UPS</carrierName>
                <methodCode>Standard</methodCode>
                <trackingNumber>123123123</trackingNumber>
                <trackingURL>http://ups.com</trackingURL>
            </trackingInfo>
        </orderStatus>
    </orderData>
</orderShipment>

1 个答案:

答案 0 :(得分:0)

使用DOMDocument::createElementNS()方法。

$namespaceUri = 'http://www.ups.com/WSDL/XOLTWS/Track/v2.0';

$document = new DOMDocument();
$order = $document->appendChild(
  $document->createElementNS($namespaceUri, 'ns2:orderShipment')
);
$order->appendChild(
  $document->createElementNS($namespaceUri, 'ns2:orderData')
);

$document->formatOutput = TRUE;
echo $document->saveXml();

输出:

<?xml version="1.0"?>
<ns2:orderShipment xmlns:ns2="http://www.ups.com/WSDL/XOLTWS/Track/v2.0">
  <ns2:orderData/>
</ns2:orderShipment>

*NS是DOM方法的名称空间感知变体。通常他们会将名称空间uri作为第一个参数。名称空间前缀仅用于“write / setter”方法。