0

Can you please tell me how I can save a two dimensional array in to a text file

if I have an array with unknown number of elements in its index value:

$two_darray[unknown][unknown];
1
  • is encoding it to a JSON an option? Commented Jul 22, 2013 at 3:26

4 Answers 4

4

You simply need to serialize this array. You can wrap it in serialize() and output this to a file. You can then use unserialize() later to decode it.

For portability, I recommend using JSON instead, with json_encode()/json_decode().

file_put_contents('someFile.json', json_encode($yourArray));
Sign up to request clarification or add additional context in comments.

2 Comments

@Orangepill, Excellent point. One other thing I forgot to mention that might influence the decision... if you need native PHP types, you will need PHP's serialization.
and for non-native classes make sure you have definitions included or an autoloader in play prior to calling unserialize or you will end up with a bunch of incomplete class objects.
3

Actually, @Brad's and @Hilmi's answers are correct, but I'm not sure using only JSON is a good advice.

You can choose

JSON

write: file_put_contents('someFile.json', json_encode($two_darray));

read: $two_darray = json_decode(file_get_contents('someFile.txt'));

XML

Look this answer

Serialized data

write: file_put_contents('someFile.txt', serialize($two_darray));

read: $two_darray = unserialize(file_get_contents('someFile.txt'));

CSV (to use with MS Excel or some DB)

$handler = fopen('someFile.csv', 'w+');
foreach ($two_darray as $one_darray) {
    fputcsv($handler, $one_darray);
}

read it with fgetcsv

and even SQLite

$db = new SQLiteDatabase('someFile.sqlite');
foreach ($two_darray as $one_darray) {
    $db->query("INSERT INTO `MyTable` VALUES (".implode(',', $one_darray).")");
}

read: $two_darray = $db->sqlite_array_query("SELECT * FROM MyTable");

EDIT Binary (for .zip or .tar.gz)

Try pack()

1 Comment

thats a nice explanation. Can you please show us how you read the value back in to an array using JSON and Serialized methods
0

You can serialize the array to a string and save it into the file, and when ever you want that array just by unserializing the file's content you'll have the array back

Comments

0
<?php
$arr = array( array('aa', 'aa'), array('bb','bb') );
file_put_contents('/tmp/test',serialize($arr));
var_dump(unserialize(file_get_contents('/tmp/test')));
?>

You can also use json_encode/json_decode instead of serialize/deserialize as suggested by @Brad above

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.