user2619381
user2619381

Reputation: 217

Creating attribute in domdocument

I have to make this type of XML :-

<?xml version="1.0" encoding="UTF-8"?>

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

   <url>

      <loc>http://www.example.com/</loc>

      <lastmod>2005-01-01</lastmod>

      <changefreq>monthly</changefreq>

      <priority>0.8</priority>

   </url>

   <url>

      <loc>http://www.example.com/catalog?item=12&amp;desc=vacation_hawaii</loc>

      <changefreq>weekly</changefreq>

   </url>
</urlset>

For which I have written this code,

 $dom = new domDocument('1.0', 'utf-8');
      $dom->formatOutput = true; 
$rootElement = $dom->createElementNS('http://www.sitemaps.org/schemas/sitemap/0.9', 'urlset');
      $sxe = simplexml_import_dom( $dom );
      $urlMain = $sxe->addChild("url");
      $loc = $urlMain->addChild("loc","http://www.example.com");
      $lastmod = $urlMain->addChild("lastmod","$date");
      $changefreq = $urlMain->addChild("changefreq","daily");
      $priority = $urlMain->addChild("priority","1");

Everything works completely fine, but for some reason xmlns for urlset is not getting added. What might be wrong here? Any suggestion would be helpful.

Upvotes: 0

Views: 71

Answers (1)

user3942918
user3942918

Reputation: 26385

You need to append the root element to the document prior to conversion to simplexml:

$rootElement = $dom->createElementNS('http://www.sitemaps.org/schemas/sitemap/0.9', 'urlset');
$dom->appendChild($rootElement);
$sxe = simplexml_import_dom( $dom );

Upvotes: 1

Related Questions