1

I have an array $urls_array, how do I only save the contents and not anything else into a file?

INPUT:

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

OUTPUT:

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

I tried using json_encode($urls_array) and serialize() and print_r(), but nothing gave me the clean result I wanted. Any help?

2
  • what about file_put_contents? Commented Aug 22, 2013 at 6:11
  • tried that too but it basically saves all the array stuff "Array([0]=>" and not just the URL Commented Aug 22, 2013 at 6:12

5 Answers 5

3

Have you tried file_put_contents?

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

The above has only a small problem: if your array is big, it will be converted to a long string before being written to the file as a whole. To avoid this memory intensive operation, loop through the array and write each item to the file sequentially:

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");
}
Sign up to request clarification or add additional context in comments.

2 Comments

this works!! guess there's magic with the join("\n") part which I didn't use earlier... genius thanks!
@NoIdeaForName: I didn't edit anything in my original code. Look at the edit history
2

Try this:

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

Here are the docs: http://php.net/manual/en/function.file-put-contents.php

Comments

2

try this code its 100% working...

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

1 Comment

OP only wants the array elements in his file, not the array structure.
1

Try this..

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.