Jasmine22 Jasmine22 - 3 months ago 14
PHP Question

Create multiple files from one file

foreach($new_files as $new_file) {
//create file
$myfile = fopen($filename, "w");

//put contents in the file
fwrite($filename, $new_file['content']);

//close the file
fclose($myfile);
}


I have this code to create a new file, I want to be able to open $filename, and create multiple files from it, with the content of new_file.
This code doesn't seem to work,all I get is one new empty file, any ideas?

Answer

Here is a working example.

You have to store data in standard structure like JSON in $filename, then read its data and make other files.

<?php

// $Data = file_get_contents($filename);
// $Data = json_decode($Data); <--- if stored as json

// Sample Data
$Data = [
    [
        'name'    => 'file1.txt',
        'content' => 'content1',
    ],
    [
        'name'    => 'file2.txt',
        'content' => 'content2',
    ],
];

foreach ($Data as $Row) {
    $File = fopen($Row['name'], 'w');
    fwrite($File, $Row['content']);
    fclose($File);
}
Comments