2012-03-15 117 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