by Nick Boss.
Here's how to create a file whose contents will be a text string. This is the equivalent of the PHP function file_put_contents.
$fs = get_file_storage();
// Prepare file record object
$fileinfo = array(
'contextid' => $context->id, // ID of context
'component' => 'mod_mymodule', // usually = table name
'filearea' => 'myarea', // usually = table name
'itemid' => 0, // usually = ID of row in table
'filepath' => '/', // any path beginning and ending in /
'filename' => 'myfile.txt'); // any filename
// Create file containing text 'hello world'
$fs->create_file_from_string($fileinfo, 'hello world');