1

我有一个数组$urls_array,我如何只将内容而不是其他任何内容保存到文件中?

输入:

Array (
  [0] => "http://google.com"
  [1] => "http://facebook.com"
  [2] => "http://yahoo.com"
)

输出:

http://google.com
http://facebook.com
http://yahoo.com

我尝试使用json_encode($urls_array)and serialize()print_r()但没有给我想要的干净结果。有什么帮助吗?

4

5 回答 5

3

你试过file_put_contents吗?

file_put_contents('filename', join("\n", $your_array));

上面只有一个小问题:如果你的数组很大,在写入整个文件之前,它会被转换成一个长字符串。为避免这种内存密集型操作,请遍历数组并将每个项目按顺序写入文件:

if(($f = fopen("filename","w")) !== FALSE) {
  array_walk($your_array, function($item) use($f) { fwrite($f, $item . "\n"); });

  // or, with an implicit loop
  // foreach($your_array as $item) fwrite($f, $item . "\n");
}
于 2013-08-22T06:12:24.090 回答
2

试试这个代码它 100% 工作...

  <?php
    $data=array("http://google.com","http://facebook.com","http://yahoo.com");
    $fp = fopen('file.txt', 'w');
    foreach($data as $key => $value){
   fwrite($fp,$value."\t");
  }
    fclose($fp);
     ?>
于 2013-08-22T06:13:21.173 回答
2

尝试这个:

file_put_contents('/path/to/file', implode("\n", $urls_array));

以下是文档: http: //php.net/manual/en/function.file-put-contents.php

于 2013-08-22T06:14:09.440 回答
1

尝试这个..

<?php
  $arr=array("ABC","DEF","GHI");
  $fp=fopen("test.txt","w+");
  foreach($arr as $key => $value){
   fwrite($fp,$value."\t");
  }
?>
于 2013-08-22T06:14:07.703 回答
0

Try this:

<?php
$myArray = Array(0 => "http://google.com", 1 => "http://facebook.com", 2 => "http://yahoo.com");
foreach($myArray as $value){
    file_put_contents("text.txt", $value."\n", FILE_APPEND);
}
?>

The main benifit of file_put_contents is that it's equivalent calling fopen() + fwrite() + fclose(), so for simple tasks like this, it can be very useful.

You can find it's manual -> HERE.

于 2013-08-22T06:26:39.490 回答