I have generated a simple xml. I want to add namespace / prefix in the xml is there a way using php DomDocument. Or do I need to use core php to replace the tags and recreate it in xml.
<?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>
Expected Output
<?xml version="1.0" encoding="UTF-8"?>
<ns2:orderShipment>
<ns2:orderData>
<ns2:productId>1</ns2:productId>
<ns2:orderStatus>
<ns2:status>Shipped</ns2:status>
<ns2:statusQuantity>
<ns2:amount>1</ns2:amount>
</ns2:statusQuantity>
<ns2:trackingInfo>
<ns2:shipDateTime>Fri, 24 Feb 2017</ns2:shipDateTime>
<ns2:carrierName>UPS</ns2:carrierName>
<ns2:methodCode>Standard</ns2:methodCode>
<ns2:trackingNumber>123123123</ns2:trackingNumber>
<ns2:trackingURL>http://ups.com</ns2:trackingURL>
</ns2:trackingInfo>
</ns2:orderStatus>
</ns2:orderData>
</ns2:orderShipment>
Use the DOMDocument::createElementNS()
method.
$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();
Output:
<?xml version="1.0"?>
<ns2:orderShipment xmlns:ns2="http://www.ups.com/WSDL/XOLTWS/Track/v2.0">
<ns2:orderData/>
</ns2:orderShipment>
*NS
are the namespace aware variants of the DOM methods. Usually they will take the namespace uri as the first argument. The namespace prefix will only be used in "write/setter" methods.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.