Php 自动生成和替换站点地图

Php 自动生成和替换站点地图,php,mysqli,sitemap,Php,Mysqli,Sitemap,我正在尝试自动替换服务器上的站点地图文件。使用php和mysqli,我生成了所需的输出,但我无法确定如何将该输出保存为.xml文件。 我读过关于用php创建、打开和编写文件的书,但我不知道如何将生成的内容放入文件中。有什么建议吗 这是我到目前为止的代码 $my_file='sitemap.xml'; $handle=fopen($my_文件,'w')或die($my_文件:'); $data=“”//如何将下面的代码作为“数据”包含? http://www. 每日的 1 尝试以下方法: $my

我正在尝试自动替换服务器上的站点地图文件。使用php和mysqli,我生成了所需的输出,但我无法确定如何将该输出保存为.xml文件。
我读过关于用php创建、打开和编写文件的书,但我不知道如何将生成的内容放入文件中。有什么建议吗

这是我到目前为止的代码

$my_file='sitemap.xml';
$handle=fopen($my_文件,'w')或die($my_文件:');
$data=“”//如何将下面的代码作为“数据”包含?
http://www.
每日的
1

尝试以下方法:

$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);
?>
$my_file='sitemap.xml';
$handle=fopen($my_文件,'w')或die($my_文件:');
$data=“”//如何将下面的代码作为“数据”包含?
//启动输出缓冲区
http://www.
每日的
1

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

这只是fopen/fwrite/fclose的简化版本。不过,正如您所注意到的,它确实会写入一个字符串

把事情安排得井井有条 方案A 可以使用以下方法生成字符串:

$string = "Hello I'm a string.";
要附加更多,可以使用

$string = $string . " And I'm another part.";
或使用以下命令的较短版本:

方案B 还可以使用如下方式缓冲任何输出(打印的内容(print()/echo/etc)):


您试图获取响应的Post代码。唯一的指针是php manual。您可以将所有输出连接在一个长字符串中,也可以使用输出缓冲区。感谢WheatBeak,以前从未使用过输出缓冲区,您的代码为我准确地解决了问题。再次感谢。
$string = $string . " And I'm another part.";
$string .= " And I'm another part.";
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);