2012-08-23 55 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')));」刪除額外的「)」 –