我正在尝试使用两个foreach
输出xml - 并将其生成的输出复制到另一个文件中。
我很困惑,我甚至不知道是否要问“如何将输出复制到其他文件”或“如何将foreach转换为字符串” - 因为写一个字符串是没问题的。
到目前为止我已经
了// clear previous contents of tutorials.xml
$myFile = "tutorials.xml";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "";
fwrite($fh, $stringData);
// here begins the string I want to write to the other file
echo <<<EOF
<?xml version="1.0" encoding="UTF-8"?>
<albums>
EOF;
foreach($albumInfo as $album) {
echo <<<EOF
<album>
<id>{$album->id}</id>
<title>{$album->title}</title>
<videos>
EOF;
}
foreach($videos as $video) // loop through our videos
{
$minutes = floor($video->duration/60);
$secondsleft = $video->duration%60;
if($secondsleft<10)
$secondsleft = "0" . $secondsleft;
echo <<<EOF
<video>
<id>{$video->id}</id>
<title>
<description>{$video->description}</description>
<duration>{$video->duration}</duration>
</video>
EOF;
}
echo <<<EOF
</album>
EOF;
?>
<?php echo '</albums>' ?>
// here ends the string I want to write to the other file
// the script below just takes the raw php and copies it over - I need the output.
<?php
copy('tutorials-job.php', 'tutorials.xml');
?>
感谢您的帮助!
答案 0 :(得分:0)
将echo替换为对变量的赋值,然后将其写入文件
echo <<<EOF
<?xml version="1.0" encoding="UTF-8"?>
<albums>
EOF;
变为
$str='
<?xml version="1.0" encoding="UTF-8"?>
<albums>
';
后者使用
$str .='
添加到字符串
答案 1 :(得分:0)
您已经表明您知道如何使用此代码的前几行将内容输出到文件。您可以将输出加载到输出缓冲区,然后将缓冲区的内容写入文件,或者代替echo
所有内容,将该数据放入字符串中,然后将该字符串写入文件。
话虽这么说,如果你没有坚持使用XML格式,你可以考虑使用像JSON这样的东西,你可以用一行代码轻松地在你的数组/对象表示之间转换为序列化表示。