php将数组元素按行写入文本文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php将数组元素按行写入文本文件相关的知识,希望对你有一定的参考价值。
比如有一个数组:
$arr = array('aa', 'bb', 'cc');
如何把它的元素写到 A.txt 中,使得 A.txt 的每一行就是数组的一个元素,即:
aa
bb
cc
$arr = array('aa', 'bb', 'cc');
$str = implode("\\r\\n", $arr);
file_put_contents("A.txt", $str);
?>追问
我试了一下,每一行文字之间还多了个空行,是不是多加了个换行符?请问怎么改?
啊,我知道了,把"\r\n"改成""就行了。谢谢!
这个函数就是把str这个数组变量写到123的文本文档里面 参考技术C
直接用foreach遍历数组,然后echo出来,然后每一行输出一个br
<?phpforeach($arr as $v)
echo $v,"<br>";
//多维数组自己脑补递归 参考技术D $theStr = "";
foreach($arr as $value)
$theStr .= $value . "\r\n";
$theFile = fopen ( "A.txt", "w" ); // 创建读取文件 if (file_exists ( "A.txt" )) // 判断文件是否存在 if (is_writable ( "A.txt" )) fwrite ( $theFile, $theStr ); fclose ( $theFile ); 第5个回答 2015-07-12
参考例子如一下
$arr = array('1', '2', '3');
$str = implode("", $arr);
file_put_contents("XX.txt", $str);
?>
php怎么将对象或者数组写入一个文本文件
第一种:<?php
$filename = \'test.txt\';
$somecontent = "this is test string.";
if (is_writable($filename))
if (!$handle = fopen($filename, \'a\'))
echo "不能打开文件 $filename";
exit;
// 将$somecontent写入到我们打开的文件中。
if (fwrite($handle, $somecontent) === FALSE)
echo "不能写入到文件 "e;$filename"e;";
exit;
echo "已把"e;$somecontent"e;写入到文件"e;$filename"e;";
fclose($handle); //将指针关闭
else
echo "文件$filename不可写.";
?>
第二种:
<?php
$filename = "test.txt";
$content = "this is test string.";
$put = file_put_contens($filename,$content);
if(!put)
exit("write failed");
echo "write success";
?>
参考资料:个人多年web开发技术
参考技术A $content = "";//数组或一个值$of = fopen('dir.txt','w');//创建并打开dir.txt
if($of)
fwrite($of,$content);//把执行文件的结果写入txt文件
fclose($of);//关闭 参考技术B $fp = fopen('1111.txt','w')
fwrite($fp,print_r($obj,true));
fwrite($fp,print_r($arr,true)); 参考技术C 先implode转为字符串,之后在file_put_contents写入文件中
以上是关于php将数组元素按行写入文本文件的主要内容,如果未能解决你的问题,请参考以下文章
使用java的输入,输出流将一个文本文件的内容按行读出,每读一行就顺序添加行号,并写入到另一个文件