Home > Back-end >  PHP - Deserialize multiple serialized object from a text file
PHP - Deserialize multiple serialized object from a text file

Time:01-08

I'm storing objects of a class on a file like this:

if (!empty($_POST)) {

    $merenda = new Merenda($_POST["name"], $_POST["numberOfDisp"], $_POST["cost"]);
    $merenda = serialize($merenda);
    file_put_contents('merende.txt', $merenda, FILE_APPEND);
}

So I'm trying to fetch all objects from another page like this:

    $serialized = file_get_contents( "merende.txt" );
    $unserialized = unserialize( $serialized );

the content of the serialized file is all in one line, with no break rows

The problem is that the unserialize() function doesn't return an array of objects but only an object passing it a serialized string. I'm looking for a way that I can get an object array from a serialized object file. How could I do it?

CodePudding user response:

You need to save serialized object in a new row in the file.

Then when you need to unserialize objects you need to read the file row by row and unserialize each row.

For example:

<?php

if (!empty($_POST)) {

    $merenda = new Merenda($_POST["name"], $_POST["numberOfDisp"], $_POST["cost"]);
    $merenda = serialize($merenda) . PHP_EOL;;
    file_put_contents('merende.txt', $merenda, FILE_APPEND);
}
<?php

$fileContent = file_get_contents( "merende.txt" );
$objects = [];
foreach (explode(PHP_EOL, $fileContent) as $row) {
    $object = unserialize($row);

    if ($object) {
        $objects[] = $object;
    }
}

It is just example to understand the idea, it can be implemented more beautifully.

  • Related