Home php How to write PHP array to file and read it from file

How to write PHP array to file and read it from file

Author

Date

Category

& lt;? php
$ bookshelf = array (
 array (
  array (
   'author' = & gt; 'L. Thick',
   'title' = & gt; 'War and Feast',
   'year' = & gt; 2005,
  ),
  array (
   'author' = & gt; 'N. Gogol-Mogol ',
   'title' = & gt; 'Dead ears',
   'year' = & gt; 2005,
  ),
 ),
 array (
  array (
   'author' = & gt; 'G. Wells',
   'title' = & gt; 'Burden Machine'
   'year' = & gt; 2009,
  ),
  array (
   'author' = & gt; 'NS. Derrows',
   'title' = & gt; 'Narzan',
   'year' = & gt; 1994,
  ),
 ),
);
$ bookshelf [] = 'SuperPuper';
object2file ($ bookshelf, 'array.txt'); 

Answer 1, authority 100%

$ filename = 'array.txt';
// Record.
$ data = serialize ($ bookshelf); // PHP format of the stored value.
// $ data = json_encode ($ bookshelf); // JSON format of the stored value.
file_put_contents ($ filename, $ data);
// Reading.
$ data = file_get_contents ($ filename);
// $ bookshelf = json_decode ($ data, TRUE); // If not TRUE then get an object, not an array.
$ bookshelf = unserialize ($ data);

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions