繁体   English   中英

仅将php数组的内容保存到文件

[英]Save only the contents of php array to file

我有一个数组$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)serialize()print_r() ,但是没有任何东西给我我想要的干净结果。 有什么帮助吗?

您是否尝试过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");
}

试试这个代码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);
     ?>

尝试这个:

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

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

尝试这个..

<?php
  $arr=array("ABC","DEF","GHI");
  $fp=fopen("test.txt","w+");
  foreach($arr as $key => $value){
   fwrite($fp,$value."\t");
  }
?>

尝试这个:

<?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);
}
?>

file_put_contents的主要file_put_contents是等效调用fopen() + fwrite() + fclose() ,因此对于像这样的简单任务,它可能非常有用。

您可以找到它的手册-> 这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM