Reputation:
I want to create an XML sitemap (for the sake of SEO), my first attempt to achieve this was by including the website main menu/navigation links using <?php include ("assets/includes/menu.inc"); ?>
:
<li><a href="index.php">Home</a></li>
<li><a href="gallery.php">Gallery</a></li>
<li><a href="contact.php">Contact</a></li>
To the following XML sitemap file:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>http://www.example.com/</loc></url>
</urlset>
I already asked a question here of "How to include PHP to XML" - apparently I can't do that, so my idea was thrown to the bin. I already Googled "How to create an automatic sitemap" but all what I have found was Sitemap Generators which I am trying to avoid.
The question is, is that even possible? to create a sitemap that will pull the links from the website main .inc file? Any ideas?
Upvotes: 1
Views: 301
Reputation: 10003
If you have the DOM
extension installed, you could load the HTML navigation, and then create an XML sitemap.
// Create an empty document, load it with your HTML
$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadHTML('<li><a href="index.php">Home</a></li>...');
// Get links
$links = array();
foreach($dom->getElementsByTagName('a') as $link){
$links[] = $link->getAttribute('href');
}
Now we have an array of relative URLs in $links
. You can now generate an XML document using the DOM
extension (recommended, but more complicated), or use your $links
directly to generate output:
<?php echo '<?xml version="1.0" encoding="UTF-8"?>'; // Be wary of "?>" in your document ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach($links as $link): ?>
<url><loc>http://www.mydomain.com<?php echo htmlspecialchars($link, ENT_XML1, 'UTF-8'); ?></loc></url>
<?php endforeach; ?>
</urlset>
Upvotes: 1