Add additional namespace to XML file

Viewed 100

I am trying in PHP to add an additional namespace to the <gpx> element of an XML file. This is the existing <gpx> element (note the namespace "stunninghikes" is not included):

<?xml version="1.0" encoding="UTF-8"?>
<gpx xmlns="http://www.topografix.com/GPX/1/1" 
    xmlns:gpsies="https://www.gpsies.com/GPX/1/0" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    creator="GPSies https://www.gpsies.com - Amden - Chapf (1296m) - Arvenb&amp;#252;el - Vorderh&amp;#246;hi - Gulmen (1788m) - Hinter H&amp;#246;hi - Niederschlag" 
    version="1.1" 
    xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd https://www.gpsies.com/GPX/1/0 https://www.gpsies.com/gpsies.xsd">
    <content>
    (Lots more content)
    </content>
</gpx>

What I would like is for the attribute xmlns:stunninghikes="https://stunninghikes.com/GPX/1/0" to be added to the <gpx> element.

I have tried numerous options of using createAttributeNS and setAttributeNS, but CANNOT get it working! This is one example of what I have tried:

$gpxDoc = new DomDocument;
$gpxDoc->load($gpxFileName);
$gpxNode = $gpxDoc->getElementsByTagName('gpx'); 
$gpxNode->createAttributeNS('https://stunninghikes.com/GPX/1/0', 'xmlns:stunninghikes');
$gpxDoc->appendChild($gpxNode);

Any ideas?

1 Answers

You were pretty close with your attempt. You aren't allowed to manually change the xmlns attributes of the document, instead you'll get a DOMException complaining about a "Namespace Error."

What you can do is create an attribute (any attribute) and the XML document will automatically be updated to include the namespace, even if you don't append it to the document:

$gpxDoc = new DomDocument;
$gpxDoc->load($gpxFileName);
$gpxDoc->createAttributeNS('https://stunninghikes.com/GPX/1/0', 'stunninghikes:dummy');
echo $gpxDoc->saveXML();

Output:

<?xml version="1.0" encoding="UTF-8"?>
<gpx xmlns="http://www.topografix.com/GPX/1/1" xmlns:gpsies="https://www.gpsies.com/GPX/1/0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:stunninghikes="https://stunninghikes.com/GPX/1/0" creator="GPSies https://www.gpsies.com - Amden - Chapf (1296m) - Arvenb&amp;#252;el - Vorderh&amp;#246;hi - Gulmen (1788m) - Hinter H&amp;#246;hi - Niederschlag" version="1.1" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd https://www.gpsies.com/GPX/1/0 https://www.gpsies.com/gpsies.xsd">

    <content>
    (Lots more content)
    </content>
</gpx>
Related