我想把数组的内容写到新文件中。
到目前为止,我的文件只包含数组的最后一个元素,而不是前两个元素。因此,文件output2.txt中的文本仅为Edward。
我是不是误解了什么?
$array = array ("Sarah", "William", "Edward");
foreach ($array as $value) {
$myfile = fopen("output2.txt", "w") or die("Unable to open file!");
fwrite($myfile,$value);
fclose($myfile);
} 发布于 2016-04-30 19:38:03
<?php
$array = array ("Sarah", "William", "Edward");
$txt = "";
foreach ($array as $value) {
$txt = $txt . $value;;
}
$myfile = fopen("output2.txt", "w+") or die("Unable to open file!");
fwrite($myfile,$txt);
fclose($myfile);
?>不要在循环中包含文件操作函数,创建一个字符串,然后将其写入文件。
就像@Dagon建议的那样,你可以简单地使用内爆函数来内爆一个数组。
<?php
$array = array ("Sarah", "William", "Edward");
$txt = implode(",", $array);
$myfile = fopen("output2.txt", "w+") or die("Unable to open file!");
fwrite($myfile,$txt);
fclose($myfile);
?>发布于 2016-04-30 19:32:47
$myfile = fopen("output2.txt", "w") or die("Unable to open file!");
$abcd = "";
foreach ($array as $value) {
$abcd .= $value;
}
fwrite($myfile,$abcd);
fclose($myfile);您每次尝试都会创建新文件,这可能会对您有所帮助
https://stackoverflow.com/questions/36954302
复制相似问题