Saurabh
Saurabh

Reputation: 139

How to write a structure into a file in PHP?

I have learned that to create a structure, I can create an array like so:

$MyStructure = array (
    'id' => '12345',
    'name'  => 'myName');

I also know, to write into a file, I can use:

file_put_contents($fileName, $myTextToSave, FILE_APPEND);

But, this function stores it in simple text format. I want to know about functions such as in C-Language: fwrite( &record, sizeof(struct myStructure), 1, fp );

Is there any function in PHP which can store data in chunks of data-structure and then retrieve it in data structure format?

Upvotes: 1

Views: 1312

Answers (2)

trixtur
trixtur

Reputation: 708

You could write your structure to a file with file_put_contents as you have outlined in your post.

You can serialize and unserialize the arrays or objects into the file using the following documentation:

http://php.net/manual/en/function.serialize.php

http://php.net/manual/en/function.unserialize.php

So it would look like this:

file_put_contents($fileName, serialize($MyStructure), FILE_APPEND);

Upvotes: 1

Marius
Marius

Reputation: 4016

Well if you must do it this way and cannot do without a database, then have a look at this:

http://php.net/manual/en/function.pack.php

But that is for storing data (binary). If you just want to store arrays in files, use serialize() or json_encode()

Upvotes: 1

Related Questions