Burndog
Burndog

Reputation: 719

PHP DOMDocument - how to add Namespace declaration?

I’m creating a dynamic sitemap.xml based on the following code

 <?php

 $dom = new DOMDocument();

 $dom->encoding = 'utf-8';
 $dom->xmlVersion = '1.0';
 $dom->formatOutput = true;

 $xml_file_name = 'SM_listings'.$mid.'.xml';

 $root = $dom->createElement('urlset');


     while(!$listings->atEnd()) {
         $url_node = $dom->createElement('url');
         $child_node_loc = $dom->createElement('loc', urlTarget.$listings->getColumnVal('invId'));
    $url_node->appendChild($child_node_loc);

    $child_node_date = $dom->createElement('lastmod', $listings->getColumnVal('Submit_date'));
    $url_node->appendChild($child_node_date);
  $root->appendChild($url_node);


 $listings->moveNext();
                            }
 $listings->moveFirst(); //return RS to first record


 $dom->appendChild($root);
 $dom->save($xml_file_name);

 echo "$xml_file_name has been successfully created";

 ?>

This works but Google is not happy there is not a Namespace declaration in the 'urlset' node. Google error: “Your Sitemap or Sitemap index file doesn't declare the expected namespace: http://www.sitemaps.org/schemas/sitemap/0.9"

If I change the code to :

$root = $dom->createElement('urlset 
xmlns=“http://www.sitemaps.org/schemas/sitemap/0.9"');

it fails to generate the xml file and references the following:

Fatal error: Uncaught exception 'DOMException' with message 'Invalid Character Error' in E:\Domain.com\siteMap-generator1.php:54 Stack trace: #0 E:\Domain.com\siteMap-generator1.php(54): DOMDocument->createElement('urlset xmlns=\\"...') #1 {main} thrown in X:\Domain.com\siteMap-generator1.php on line 54

In testing I see that the node requires a very specific name/string:

$root = $dom->createElement(‘urlset 123’);  FAILS
$root = $dom->createElement(‘urlset-123');  WORKS

BUT the closing node also balances such as:

<url>
    <urlset-123>
        <loc>some value</loc>
    </urlset-123>
<url>

QUESTION: How to properly add the required Namespace and also not have it as part of the closing node element?

I tried the following to append the value but that also failed:

$dom->nameSpace = ' http://www.sitemaps.org/schemas/sitemap/0.9';

$root = $dom->createElement('urlset + nameSpace');

Upvotes: 4

Views: 4089

Answers (1)

ishegg
ishegg

Reputation: 9937

Use DOMDocument::createElementNS() like this:

$root = $dom->createElementNS("http://www.sitemaps.org/schemas/sitemap/0.9", "urlset");

Upvotes: 3

Related Questions