2012-08-23 57 views
1

我有以下代码,但我想要适当的站点地图标准。如何创建动态的XML站点地图

我的代码

$xml = new DomDocument('1.0', 'utf-8'); 
$xml->formatOutput = true; 
$products= $xml->createElement('url'); 
$product = $xml->createElement('url'); 
$xml->appendChild($products); 
$products->appendChild($product); 
$product->appendChild(new DomAttr('loc', '123')); 
$xml->save("data.xml"); 

但表示代码的输出是LILE:

<?xml version="1.0" encoding="utf-8"?> 
<url> 
<url loc="123"/> 
</url> 

但我想下面的标准...

<?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>2012-08-11T04:08:53+01:00</lastmod> 
     <changefreq>monthly</changefreq> 
     <priority>0.5</priority> 
    </url> 
</urlset> 

请在这方面帮助我。

回答

4

您已经证明可以通过您的语法创建XML文档 - 只需重新创建标准模板即可。

例如起见,我会假装你的网站信息被存储在阵列,例如:

$yourSiteContent = array(
    array('permalink' => 'http://www.somesite.com/someurl1', 'updated' => '2012-08-11T04:08:53+01:00'), 
    array('permalink' => 'http://www.somesite.com/someurl2', 'updated' => '2012-09-11T04:08:53+01:00'), 
    array('permalink' => 'http://www.somesite.com/someurl3', 'updated' => '2012-10-11T04:08:53+01:00') 
); 

然后坚持回你的例子:

$xml = new DomDocument('1.0', 'utf-8'); 
$xml->formatOutput = true; 

// creating base node 
$urlset = $xml->createElement('urlset'); 
$urlset -> appendChild(
    new DomAttr('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9') 
); 

    // appending it to document 
$xml -> appendChild($urlset); 

// building the xml document with your website content 
foreach($yourSiteContent as $entry) 
{ 

    //Creating single url node 
    $url = $xml->createElement('url'); 

    //Filling node with entry info 
    $url -> appendChild($xml->createElement('loc', $entry['permalink'])); 
    $url -> appendChild($lastmod = $xml->createElement('lastmod', $entry['updated'])); 
    $url -> appendChild($changefreq = $xml->createElement('changefreq', 'monthly')); 
    $url -> appendChild($priority = $xml->createElement('priority', '0.5')); 

    // append url to urlset node 
    $urlset -> appendChild($url); 

} 

$xml->save("data.xml"); 

剩下的就是给你。

+0

工作正常..请从下面的行“..ap/0.9')));”删除额外的“)” –