我为我的动态网站设计了一个只有index.PHP的网站地图文件的PHP版本。结果如下:http://www.oddsnavigator.eu/sitemap.php
现在,我需要一种方法来将这些结果导出到sitemap.xml文件,或者使这一结果对xml和Google友好。这是代码:
<?PHP
$SQL="boring query";
$num_rows = mysql_num_rows(mysql_query($SQL));
echo $num_rows , "</BR>";
$result = mysql_query($SQL);
if($result === FALSE) { die(mysql_error());}
while($db_field=mysql_fetch_assoc($result)) {
$goto = "http://oddsnavigator.eu/?display=0&sport=" . $db_field['sportid'] . "&day=all&league=" . $db_field['stageid'];
$title = $db_field['sportname'] . " " . $db_field['tempname'] . " " . $db_field['stagename'] . " Sports Betting Odds Comparison - OddsNavigator.eu";
echo "<a href='$goto' title='$title'>" , $db_field['sportname'] , " " , $db_field['tempname'] , " " , $db_field['stagename'] , "</a>" , "</BR>";
}
?>
有什么想法吗?
在您的代码$goto
包含url中,将所有这些url存储在一个名为$URLs的数组中,然后使用以下函数
我希望代码进入class
,如果不是用$variable
替换$this->variable
的话。
//$urls = array();
$compress = true;
function save ()
{
if (empty($this->urls)) return;
$file = "sitemap.xml{$this->compress}";
$xml = '<?xml version="1.0" encoding="UTF-8"?>' . "'n";
$xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "'n";
foreach ($this->urls as $url)
{
$xml .= ' <url>' . "'n";
if (is_array($url)) {
foreach ($url as $key => $value) $xml .= " <{$key}>{$value}</{$key}>'n";
}
else {
$xml .= " <loc>{$url}</loc>'n";
}
$xml .= ' </url>' . "'n";
}
$xml .= '</urlset>' . "'n";
$this->urls = array();
if (!empty($this->compress)) $xml = gzencode($xml, 9);
$fp = fopen(BASE_URI . $file, 'wb');
fwrite($fp, $xml);
fclose($fp);
}
以下是解决方案的完整代码,如果有人遇到同样的问题,可供将来参考。该代码使用SQL查询从数据库中提取信息,然后将信息传递到XML文件中。
<?PHP
$SQL="boring query";
$result = mysql_query($SQL);
//assigning the value of the URL which will be moved to sitemap.xml
while($db_field=mysql_fetch_assoc($result)) {
$urls[] = "http://oddsnavigator.eu/?display=0&sport=" . $db_field['sportid'] . "&day=all&league=" . $db_field['stageid'];
}
mysql_close($db_handle);
$compress = true;
//setting the sitemap.xml header
$xml = "<?xml version='1.0' encoding='UTF-8'?>" . "'n";
$xml .= "<urlset xmlns='http://www.sitemaps.org/schemas/sitemap/0.9'>" . "'n";
//adding each element
foreach ($urls as $url)
{
$xml .= ' <url>' . "'n";
if (is_array($url)) {
foreach ($url as $key => $value) $xml .= " <{$key}>{$value}</{$key}>'n";
}
else {
$xml .= " <loc>{$url}</loc>'n";
$xml .= " <changefreq>hourly</changefreq>'n";
}
$xml .= ' </url>' . "'n";
}
$xml .= '</urlset>' . "'n";
$urls = array();
//writing to file
$fp = fopen('sitemap.xml', 'wb');
fwrite($fp, $xml);
fclose($fp);
?>
您可以使用Smarty这样的模板引擎。
这将允许您轻松地循环完成XML的创建。
或者你可以使用[http://php.net/manual/en/book.simplexml.phpSimpleXML]。
如果您已经使用了模板引擎,那么这可能是最快、最简单的解决方案。否则,我将使用SimpleXML。