2010-01-06 4 views
10

Sto provando a formattare visivamente come appare il mio file XML quando viene emesso. In questo momento se vai su here e vedi la fonte vedrai come si presenta il file.Formato documento XML creato con PHP - DomDocument

Il PHP che ho che crea il file è: (Nota, $ links_array è un array di URL)

 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); 
    } 

Come si può dire guardando la fonte, il file non è più leggibile Mi piacerebbe che fosse. C'è un modo per me di formattare i nodi?

Grazie,
Levi

+0

È possibile aggiungere un'intestazione xml e aprirlo in FireFox. Questo mostrerà una bella versione formattata dal tuo documento xml –

risposta

9

Checkout l'impostazione formatOutput in DOMDocument.

$sitemap->formatOutput = true 
+1

Questo è esattamente quello che stavo cercando. Grazie! – Levi

0

non solo PHP, v'è un foglio di stile per XML: XSLT, che possono formato XML in sth sembra buono.

+0

Ah ok, ho già fatto alcuni fogli di stile XSLT di base. Speravo che ci fosse un modo per inserire interruzioni di riga almeno dopo aver creato un nodo con PHP. – Levi

+0

risposta dal formato precedenteOutput fa il lavoro? la tua domanda sembra sbagliata in questo modo .... – joetsuihk