I'm trying to have my sitemap update automatically as pages are added. I'm defining var containing the child name I need, which is including a colon character. PHP or XML is removing the colon and word to the right or left of it. How can I keep that colon in the child elements name?
I'm using this:
<?php
$imagechild = 'image:image';
$imageloc = 'image:loc';
$xml=simplexml_load_file("sitemap.xml");
$map = $xml->addChild('url');
$map->addChild('loc', "http:/some website".$page_path);
$img = $map->addChild($imagechild);
$img->addChild($imageloc, $img_link);
$xml->saveXML('sitemap.xml');
?>
I'm getting this:
<url>
<loc>web url</loc>
<image>
<loc>image url</loc>
</image>
</url>
I need this
<url>
<loc>web url</loc>
<image:image>
<loc>image url</loc>
</image:image>
</url>
Thank you in advance!
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>