我试图自动替换服务器上的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);
?>
发布于 2017-06-02 15:58:18
试着做这样的事情:
$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);
?>发布于 2017-06-02 16:05:42
有几种方法可以将数据保存到文件中,其中最简单的方法之一就是(如手册中所引用的)。
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.";或者使用赋值算子的较短版本
$string .= " And I'm another part.";备选方案B
也可以缓冲任何输出(打印的东西(print()/echo/等等)。像这样使用开始:
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);https://stackoverflow.com/questions/44332629
复制相似问题