在PHP中将结果输出复制到另一个文件
我正在尝试输出一个xml的双层foreach
- 并且只将结果的输出复制到另一个文件中。在PHP中将结果输出复制到另一个文件
我很困惑,我甚至不知道是否要问“如何将输出复制到其他文件”或“如何将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');
?>
谢谢您的帮助!
您已经证明您知道如何使用此代码的前几行将内容输出到文件。您可以将输出加载到输出缓冲区中,然后将缓冲区的内容写入文件,或者将所有内容都写入该字符串,然后将该字符串写入文件。这就是说,如果你没有停留在XML格式上,你可能会考虑使用类似JSON的东西,你可以轻松地在你的数组/对象表示到你的序列化表示之间用一行代码进行转换。
替换回波与赋值给一个变量然后写该文件
echo <<<EOF
<?xml version="1.0" encoding="UTF-8"?>
<albums>
EOF;
变得
$str='
<?xml version="1.0" encoding="UTF-8"?>
<albums>
';
后者使用
$str .='
添加到字符串
谢谢@Dagon。问题是 - 如果我在那里有一个foreach(我这样做)。现在我的输出只是一个专辑。 – itamar
@ItamarOKestenbaum我没有看到该问题'$ str。='添加到循环中的str – 2012-12-11 21:45:03
用分配给变量替换回声,然后将其写入文件。 – 2012-12-11 19:38:43