PHP脚本自动转换sitemap.xml到格式良好的可点击sitemap.html


PHP script to automatically convert sitemap.xml to well formatted clickable sitemap.html?

我有我的网站的站点地图在一个XML文件在这个格式:

<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns:xhtml="http://www.w3.org/1999/xhtml" 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" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>http://www.mywebsite.com//index.html</loc>
    <lastmod>2014-08-16</lastmod>
    <priority>0.5</priority>
  </url>
  <url>
// ... etc.

我如何自动从这个XML文件创建一个HTML页面,其中包含一个格式良好的,美观的,可点击的站点地图,为我的网站的访问者?理想情况下,这应该是一个PHP脚本,输出所需的HTML到浏览器。

编辑:我已经创建了一些代码,您可以在接受的解决方案中查看。如何优化这段代码?

由于到目前为止没有人提供解决方案,我编写了我自己的解决方案:

<?php
$thisbasedir = '../mywebsite/';
$dom = new DomDocument();
$dom->load($thisbasedir . "sitemap.xml");
$data = $dom->getElementsByTagName('loc');
echo '<!DOCTYPE html>';
echo '<HTML>';
echo '<HEAD>';
echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
echo '</HEAD>';
echo '<BODY>';
echo ("<table>");
foreach ($data as $node)
{
    echo '<tr>';
    $thisurl = $node->textContent;
    $thisbasename = basename($thisurl);
    $thistitle = get_title_tag_from_htmlpage($thisbasedir . $thisbasename);
    $thisdescription = get_description_from_htmlpage($thisbasedir . $thisbasename);
    echo ("<td>" .
          '<a href="' . $thisurl . '">' .
              $thistitle . ' (' . $thisdescription . ')' .
          '</a>' .
          "</td>");
    echo '</tr>';
}
echo ("</table>");
echo '</BODY>';
echo '</HTML>';
function get_description_from_htmlpage($ahtmlfile)
{
    $tags = get_meta_tags($ahtmlfile);
    $thisdescription = $tags['description'];
    if (isset($thisdescription))
        return $thisdescription;
    else
        return 'No description';
}
function get_title_tag_from_htmlpage($ahtmlfile)
{
    $thisfilecontents = file_get_contents($ahtmlfile);
    if (preg_match('/<title>(.+)<'/title>/', $thisfilecontents, $matches) && isset ($matches[1]))
        return $matches[1];
    else
        return "No Title";
}
?>