Levi
Levi

Reputation: 12472

Format XML Document created with PHP - DOMDocument

I am trying to format visually how my XML file looks when it is output. Right now if you go here and view the source you will see what the file looks like.

The PHP I have that creates the file is: (Note, $links_array is an array of urls)

        header('Content-Type: text/xml');
        $sitemap = new DOMDocument;
        
        // create root element
        $root = $sitemap->createElement("urlset");
        $sitemap->appendChild($root);
         
        $root_attr = $sitemap->createAttribute('xmlns'); 
        $root->appendChild($root_attr); 

        $root_attr_text = $sitemap->createTextNode('http://www.sitemaps.org/schemas/sitemap/0.9'); 
        $root_attr->appendChild($root_attr_text); 

        
        
        foreach($links_array as $http_url){
        
                // create child element
                $url = $sitemap->createElement("url");
                $root->appendChild($url);
                
                $loc = $sitemap->createElement("loc");
                $lastmod = $sitemap->createElement("lastmod");
                $changefreq = $sitemap->createElement("changefreq");
                
                $url->appendChild($loc);
                $url_text = $sitemap->createTextNode($http_url);
                $loc->appendChild($url_text);
                
                $url->appendChild($lastmod);
                $lastmod_text = $sitemap->createTextNode(date("Y-m-d"));
                $lastmod->appendChild($lastmod_text);
                
                $url->appendChild($changefreq);
                $changefreq_text = $sitemap->createTextNode("weekly");
                $changefreq->appendChild($changefreq_text);
                
        }
        
        $file = "sitemap.xml";
        $fh = fopen($file, 'w') or die("Can't open the sitemap file.");
        fwrite($fh, $sitemap->saveXML());
        fclose($fh);
    }

As you can tell by looking at the source, the file isn't as readable as I would like it to be. Is there any way for me to format the nodes?

Thanks,
Levi

Upvotes: 10

Views: 6965

Answers (2)

Anurag
Anurag

Reputation: 141859

Checkout the formatOutput setting in DOMDocument.

$sitemap->formatOutput = true

Upvotes: 10

joetsuihk
joetsuihk

Reputation: 534

not just PHP, there is a stylesheet for XML: XSLT, which can format XML into sth looks good.

Upvotes: 0

Related Questions