如何让PHP回显XML标签?

时间:2012-03-15 13:31:23

标签: php html xml sitemap

我正在开发一个拥有大约3,000-4,000个动态生成页面的网站,我正在寻找更新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标签(我只是想将其复制并粘贴到我的站点地图文件中)?

3 个答案:

答案 0 :(得分:18)

在文件开头添加以下代码:

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

通过使用此标头提供响应,浏览器不会尝试将其解析为XML,而是以纯文本形式显示完整响应。

答案 1 :(得分:5)

这是我使用的脚本。它以适当的xml格式回显,供Google阅读为站点地图。

<?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;
?>

答案 2 :(得分:4)

您需要转义标记,否则,您的浏览器会尝试渲染它们:

echo htmlentities('your xml strings');