If an element name contains a :
then the part before the :
is the namespace prefix. If you are using namespace prefixes then you need to define the namespace somewhere in the document.
Check the manual of SimpleXmlElement::addChild()
. You need to pass the namespace uri as the third element in order to make it work:
$img = $map->addChild($imagechild, '', 'http://your.namspace.uri/path');
I would encourage you to use the DOMDocument
class in favour of the simple_xml extension. It can handle namespaces much more properly. Check this example:
Assuming you have this xml:
<?xml version="1.0"?>
<map>
</map>
And this PHP code:
$doc = new DOMDocument();
$doc->load("sitemap.xml");
$map = $doc->documentElement;
// Define the xmlns "image" in the root element
$attr = $doc->createAttribute('xmlns:image');
$attr->nodeValue = 'http://your.namespace.uri/path';
$map->setAttributeNode($attr);
// Create new elements
$loc = $doc->createElement('loc', 'your location comes here');
$image = $doc->createElement('image:image');
$imageloc = $doc->createElement('loc', 'your image location comes here');
// Add them to the tree
$map->appendChild($loc);
$image->appendChild($imageloc);
$map->appendChild($image);
// Save to file
file_put_contents('sitemap.xml', $doc->saveXML());
You'll get this output:
<?xml version="1.0"?>
<map xmlns:image="http://your.namespace.uri/path">
<loc>your location comes here</loc>
<image:image>
<loc>your image location comes here</loc>
</image:image>
</map>