【问题标题】:How do I get PHP to echo XML tags?如何让 PHP 回显 XML 标签?
【发布时间】:2012-04-01 00:27:45
【问题描述】:

我正在开发一个包含大约 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 标签(我只想将其复制并粘贴到我的站点地图文件中)?

【问题讨论】:

    标签: php html xml sitemap


    【解决方案1】:

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

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

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

    【讨论】:

    • 我发现使用这个:header("Content-type: text/xml");会很好地格式化输出。
    【解决方案2】:

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

    【讨论】:

    • 所以您实际上并没有设置 XML 文件,而是在每次抓取网站时动态生成它?
    • @pennstate_fanboy 是的,每次您访问页面 /sitemap.php 时,它都会从它知道的所有页面生成站点地图。我就是这样做的,节省了我大量的时间! :)
    • 这很有道理,我想我必须遵循相同的路线,感谢您的洞察力。
    【解决方案3】:

    你需要对标签进行转义,否则你的浏览器会尝试渲染它们:

    echo htmlentities('your xml strings');
    

    【讨论】:

    • 仅供参考:echo 不是函数,因此不需要括号。
    猜你喜欢
    • 1970-01-01
    • 2010-11-26
    • 2017-11-30
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    • 1970-01-01
    相关资源
    最近更新 更多