各エコーを変更して、行を文字列変数に追加することもできます。たとえば、次のようにします。
// Instead of
echo '<?xml version="1.0"?>';
echo '';
// etc.
$xml = '<?xml version="1.0"?>';
$xml .= '';
// and so on
次に、ファイル関数の1つを使用してファイルに保存します。 file_put_contents
は簡単な方法です。
file_put_contents("/path/to/file.xml", $xml);
もっと頑強な解決策を望むなら、 DOM モジュールを使ってXML構造を構築することができます:
$document = new DOMDocument("1.0");
$root = $document->createElement("urlset");
$root->setAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
$document->appendChild($root);
while ($row = mysql_query($query)) {
$item = $document->createElement("url");
$root->append($item);
//etc.
}
echo $document->saveXML();