如何让 PHP 回显 XML 标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9720717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:29:53  来源:igfitidea点击:

How do I get PHP to echo XML tags?

phphtmlxmlsitemap

提问by William Orazi

I'm working on a site that has about 3,000-4,000 dynamically generated pages, and I'm looking to update the XML sitemap. I've tried using online generators in the past, and they never seem to capture all the pages correctly, so I was just going to do something myself. Basically I have something like:

我正在处理一个包含大约 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();
?>

Now short of having PHP write it to a text file, is there a way that I can force it to echo the actual XML tags (I just want to copy and paste it into my sitemap file)?

现在还没有让 PHP 将它写入文本文件,有没有一种方法可以强制它回显实际的 XML 标签(我只想将其复制并粘贴到我的站点地图文件中)?

回答by Rob W

Add the following code at the beginning of your file:

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

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

By serving the response using this header, the browser will not try to parse it as XML, but show the full response as plain text.

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

回答by Rick Kuipers

This is the script I use. It echos in proper xml format for Google to read as a sitemap.

这是我使用的脚本。它以适当的 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;
?>

回答by Yaniro

You need to escape the tags, otherwise, your browser will try to render them:

您需要对标签进行转义,否则,您的浏览器将尝试呈现它们:

echo htmlentities('your xml strings');