2012-03-15 50 views
4

我正在一個擁有大約3,000-4,000個動態生成頁面的網站上工作,我正在尋找更新XML站點地圖。過去我嘗試過使用在線生成器,他們似乎從未正確捕獲所有頁面,所以我只是自己做一些事情。基本上我有這樣的:如何讓PHP回顯XML標籤?

<?php 
require('includes/connect.php'); 
$stmt = $mysqli->prepare("SELECT * FROM db_table ORDER BY column ASC"); 
$stmt->execute(); 
$stmt->bind_result($item1, $item2, $item3); 
while($row = $stmt->fetch()) { 
    echo '<url><br /> 
    <loc>http://www.example.com/section/'.$item1.'/'.$item2.'/'.$item3.'</loc> 
    <br /> 
    <lastmod>2012-03-15</lastmod> 
    <br /> 
    <changefreq>monthly</changefreq> 
    <br /> 
    </url> 
    <br /> 
    <br />'; 
} 
$stmt->close(); 
$mysqli->close(); 
?> 

現在短期有PHP寫入到一個文本文件,是有辦法,我可以迫使它呼應了實際的XML標記(我只是想複製並粘貼到我的網站地圖文件)?

回答

14

在你的文件的開頭添加以下代碼:

header('Content-Type: text/plain'); 

通過使用此頭服務響應時,瀏覽器將不會嘗試分析它爲XML,但顯示完整的響應爲純文本。

+0

Haha..wow有時它的最簡單的答案...謝謝! – 2012-03-15 13:37:59

+0

我發現使用這個:header(「Content-type:text/xml」);會很好地格式化輸出。 – stuthemoo 2015-04-13 02:14:42

5

這是我使用的腳本。它以適當的xml格式迴應谷歌閱讀爲網站地圖。

<?php 
header("Content-type: text/xml"); 
$xml_output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; 
$xml_output .= "<urlset 
     xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" 
     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" 
     xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9 
      http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">\n"; 

$xml_output .= "<url>\n"; 
$xml_output .= " <loc>http://www.mydomain.com/page1</loc>\n"; 
$xml_output .= "</url>\n"; 

$xml_output .= "<url>\n"; 
$xml_output .= " <loc>http://www.mydomain.com/page2</loc>\n"; 
$xml_output .= "</url>\n"; 

$xml_output .= "</urlset>"; 

echo $xml_output; 
?> 
+0

因此,您實際上沒有設置XML文件,但每次爬網時都會生成它。 – 2012-03-15 13:38:34

+0

@pennstate_fanboy是的,每次訪問頁面/sitemap.php時,它都會從它知道的所有頁面生成一個站點地圖。這就是我的方式,節省了我的時間! :) – 2012-03-15 13:39:14

+0

這很有道理,我想我必須遵循相同的路線,謝謝你的洞察力。 – 2012-03-15 13:40:23

3

你需要躲避的標籤,否則,您的瀏覽器將嘗試使其:

echo htmlentities('your xml strings'); 
+2

供參考:'echo'不是一個函數,所以不需要parens。 – 2012-03-15 13:37:18