How do I get PHP to echo XML tags?
Asked Answered
G

3

9

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:

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

Garda answered 15/3, 2012 at 13:31 Comment(0)
B
24

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.

Belcher answered 15/3, 2012 at 13:33 Comment(1)
I found using this: header("Content-type: text/xml"); would format the output nicely.Pittance
M
7

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

echo htmlentities('your xml strings');
Mycobacterium answered 15/3, 2012 at 13:34 Comment(1)
FYI: echo is not a function, so the parens are not needed.Belcher
H
6

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

<?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;
?>
Hedwig answered 15/3, 2012 at 13:34 Comment(3)
So you don't actually have a set XML file, but you're generating it on the fly each time the site is crawled?Garda
@pennstate_fanboy Yep, every time you visit the page /sitemap.php it will generate a sitemap from all the pages it knows. That's how I do it, saves me heaps of time! :)Hedwig
That makes perfect sense, I think I'll have to follow the same route, thanks for the insight.Garda

© 2022 - 2024 — McMap. All rights reserved.