格式化使用PHP创建的XML文档 - DomDocument

时间:2022-10-20 18:36:28

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.

我试图直观地格式化我的XML文件在输出时的外观。现在,如果你去这里查看源代码,你会看到文件的样子。

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

我创建该文件的PHP是:(注意,$ links_array是一个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);
    }

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

谢谢,李维

2 个解决方案

#1


9  

Checkout the formatOutput setting in DOMDocument.

检查DOMDocument中的formatOutput设置。

$sitemap->formatOutput = true

#2


0  

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

不仅仅是PHP,还有一个XML样式表:XSLT,它可以将XML格式化为好看。

#1


9  

Checkout the formatOutput setting in DOMDocument.

检查DOMDocument中的formatOutput设置。

$sitemap->formatOutput = true

#2


0  

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

不仅仅是PHP,还有一个XML样式表:XSLT,它可以将XML格式化为好看。