Page 1 of 1

FWRITE the content of an array ? Help ^_^

Posted: Sun Aug 13, 2006 8:47 am
by derceto
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Hello!

So, it might sound pretty easy, but I can't figure out how to export the content of an array to a file.
I use :

Code: Select all

<?php
$filename = 'book.dat';
$list = $_SESSION['book'];
$handle = fopen($filename, 'wb');
fwrite($handle, $list);
fclose($handle);
?>
When I open the file saved on the hard drives, instead of including all the records of the 'book' array, it only ouptuts :
"array"
weights 5 bytes!

Oh btw, will this work to get back the content of the string :

Code: Select all

<?php
$filename = 'book.dat';
$handle = fopen ($filename, "rb");
$contents = fread ($handle, filesize ($filename));
fclose ($handle);
echo $contents;
?>
Thanks for your help ... :D


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Sun Aug 13, 2006 9:27 am
by volka
is $_SESSION['book'] an array of strings? If so, try

Code: Select all

foreach($_SESSION['book'] as $b) {
	fwrite($handle, $b);
	fwrite($handle, "\n");
}
derceto wrote:$contents = fread ($handle, filesize ($filename));
see http://de2.php.net/file_get_contents

Posted: Sun Aug 13, 2006 9:47 am
by bokehman
Or if you want it in an arry when you open it just use file().

Posted: Sun Aug 13, 2006 11:27 am
by Ambush Commander
Also check out implode()

Posted: Sun Aug 13, 2006 12:25 pm
by Weirdan
and var_export($array,true)...
and serialize()...

Image

Posted: Sun Aug 13, 2006 12:27 pm
by Ambush Commander
Well, if I had an array of strings, and had to write it to a file, I'd file_put_contents($filename, implode("\n", $array));

Posted: Sun Aug 13, 2006 12:33 pm
by Weirdan
AC, what if those strings could have \n's in them?

Posted: Sun Aug 13, 2006 12:35 pm
by Ambush Commander
Aha. My goof, I thought we were talking about an array of lines (I even said array of strings, hmmm). This does not seem to be the case, rereading the parent post.

Use serialize(). Definitely.