自动生成和替换站点地图

时间:2017-06-02 15:36:02

标签: php mysqli sitemap

我正在尝试自动替换服务器上的站点地图文件。使用php和mysqli,我生成了所需的输出,但我无法弄清楚如何将该输出保存为.xml文件。
我已经阅读过有关使用php创建,打开和编写文件的内容,但我无法弄清楚如何获取生成的内容并将其放入文件中。有什么指针吗?

到目前为止,这是我的代码......



$my_file = 'sitemap.xml';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
$data=""; //how do I include the code below as my 'data'?

<?php echo"<?xml version=\"1.0\" encoding=\"utf-8\" ?>"; ?>
<?php 
include "connectScript.php";
$date = date("Y-m-d");
header("Content-type: text/xml");
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php
$baseUrl="mysite.co.uk/page.php";
$query = "SELECT DISTINCT topic FROM db";
$result = $conn->query($query) or die (mysql_error($query));
while($row = $result->fetch_assoc()) {
$topic = $row['topic'];
$topic = "$baseUrl?t=${topic}";
?>
<url>
<loc>http://www.<?php echo $topic; ?></loc>
<lastmod><?php echo $date; ?></lastmod>
<changefreq>daily</changefreq>
<priority>1.00</priority>
</url>
<?php
}
?>
</urlset>

<?php
fwrite($handle, $data);
?>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

$my_file = 'sitemap.xml';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
$data=""; //how do I include the code below as my 'data'?

<?php ob_start();?>  //start the output buffer

<?php echo"<?xml version=\"1.0\" encoding=\"utf-8\" ?>"; ?>
<?php 
include "connectScript.php";
$date = date("Y-m-d");
//header("Content-type: text/xml");//remove this, this isn't an xml file it's a php file creating xml
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php
$baseUrl="mysite.co.uk/page.php";
$query = "SELECT DISTINCT topic FROM db";
$result = $conn->query($query) or die (mysql_error($query));
while($row = $result->fetch_assoc()) {
$topic = $row['topic'];
$topic = "$baseUrl?t=${topic}";
?>
<url>
<loc>http://www.<?php echo $topic; ?></loc>
<lastmod><?php echo $date; ?></lastmod>
<changefreq>daily</changefreq>
<priority>1.00</priority>
</url>
<?php
}
?>
</urlset>

<?php
$data = ob_get_clean();  // set everything that was output above to the $data variable
fwrite($handle, $data);
?>

答案 1 :(得分:0)

有几种方法可以将数据保存到文件中,其中一种最简单的方法是(从手册中引用)

int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )

这只是fopen / fwrite / fclose的简化版本。然而,它确实会像你注意到的那样写一个字符串。

以字符串形式获取

选项A

可以使用以下命令构建字符串:

$string = "Hello I'm a string.";

要附加更多内容,您可以使用

$string = $string . " And I'm another part.";

或使用assignment operator的较短版本:

$string .= " And I'm another part.";

选项B

也可以使用ob_start缓冲任何输出(打印的东西(print()/ echo / etc.),如下所示:

ob_start();

echo "Hello i'm a string.";
echo "And I'm another part.";
// do whatever more you need.

$content = ob_get_clean();
file_put_contents('file.txt', $content);
相关问题