Writing Array To File

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Monotoko
Forum Commoner
Posts: 64
Joined: Fri Oct 26, 2007 4:24 pm

Writing Array To File

Post by Monotoko »

Hello fellow developers...i was wondering if i could get some of your insight into this problem i appear to be having

I need to know how to save an array into a .txt document as i cannot figure out how to do it.

Here is what i have so far:

Code: Select all

<?php
//Hold server IP
$ip_hold = $_SERVER['SERVER_ADDR'];
$ip_write = "The IP of the server that send this log is ".$ip_hold."";
//Open www directory
$dir = opendir("../../");
$count = 0;
$count2 = 0;
 
//Put all folders into an array
while (($file = readdir($dir)) !== false)
{
$files[$count]=$file;
$count++;
}
closedir($dir);
 
while ($count2 != $count)
{
$temp = $files[$count2];
$direc = "../../$temp";
 
if(is_dir($direc))
    {
        $filename = "../../$temp/pubstermx/inc/pubsterdomainconfig.php";
        if (file_exists($filename))
                {
            require $filename;
                $domaincount++;
                $domainarray[$domaincount] = $DOMAIN_NAME;
                echo "$domaincount ";
                }
        $count2++;
    }
}
?>
What i would like to do now is save is the array domainarray into a text document, which contains all of the domain names which it needs, but i am not 100% certain of how to do that
Does anyone have any ideas?

Thank you ^.^

~Daniel
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Writing Array To File

Post by jackpf »

fwrite() maybe? Or file_put_contents()?
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Re: Writing Array To File

Post by Ollie Saunders »

I need to know how to save an array into a .txt document as i cannot figure out how to do it.

Code: Select all

file_put_contents($filename, implode(PHP_EOL, $array));
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: Writing Array To File

Post by McInfo »

To save an array to a file, first convert it to a string with serialize(). The array can be recovered with unserialize(). If you're asking about saving a list to a file, use Ollie's solution.

Edit: This post was recovered from search engine cache.
Last edited by McInfo on Wed Jun 16, 2010 6:47 pm, edited 1 time in total.
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Writing Array To File

Post by jackpf »

Yeah...you weren't very specific...
Post Reply