首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Fwrite in foreachloop PHP

Fwrite in foreachloop PHP
EN

Stack Overflow用户
提问于 2016-04-30 19:28:33
回答 2查看 2.8K关注 0票数 1

我想把数组的内容写到新文件中。

到目前为止,我的文件只包含数组的最后一个元素,而不是前两个元素。因此,文件output2.txt中的文本仅为Edward。

我是不是误解了什么?

代码语言:javascript
复制
$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);
} 
EN

回答 2

Stack Overflow用户

发布于 2016-04-30 19:38:03

代码语言:javascript
复制
<?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建议的那样,你可以简单地使用内爆函数来内爆一个数组。

代码语言:javascript
复制
<?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);
?>
票数 0
EN

Stack Overflow用户

发布于 2016-04-30 19:32:47

代码语言:javascript
复制
$myfile = fopen("output2.txt", "w") or die("Unable to open file!");
$abcd = "";
foreach ($array as $value) {
    $abcd .= $value;       
} 

fwrite($myfile,$abcd);
fclose($myfile);

您每次尝试都会创建新文件,这可能会对您有所帮助

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36954302

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档