Showing posts with label hook_cron. Show all posts
Showing posts with label hook_cron. Show all posts

Tuesday 8 June 2021

How to generate csv file from table data and save in specific path?

 A simple way to generate a CSV file from a database table is the "file_put_contents" function. here we are giving an example of this.

Code:

// Given exmaple is relate from drupal query..

function array2csv($data, $delimiter = ',', $enclosure = '"', $escape_char = "\\")

{

    $f = fopen('php://memory', 'r+');

    foreach ($data as $item) {

        fputcsv($f, $item, $delimiter, $enclosure, $escape_char);

    }

    rewind($f);

    return stream_get_contents($f);

}


$data = array();  
$watchdog_results = db_query("SELECT wid,uid,type,message,severity,link,location,referer,hostname,timestamp FROM watchdog")->fetchAll();

if(!empty($watchdog_results)){

// for adding first Header row

$data[] = array(

  'wid',

  'uid',

  'type',

  'message',

  'severity',

  'link',

  'location',

  'referer',

  'hostname',

  'timestamp',   

);

// for adding content rows

foreach($watchdog_results as $line){

   $data[] = $line;  

}

}

$array = json_decode(json_encode($data), true);

$csdata = array2csv($array);

file_put_contents('/code/watchdog-report.csv', $csdata);

// here "/code/watchdogcustom-report.csv" is our located file path and filename, you can write filename as you want and also locate in any path.

In Drupal, you can use this code anywhere you want like, in any controller or hook_cron function, etc.


Note: If have any suggestions or issue regarding 'How to generate csv file from table data and save in specific path?' then you can ask by comments. 

Monday 19 April 2021

How to permanent delete unused files in Drupal 8?

Drupal 8, we can programmatically delete our unused files(assets) easily. we just have to write the code in custom module file in `hook_cron` function. After put the code and clear the cache whenever you hit the cron manually or automatically will run this code will execute.

Code:

/**

 * override hook_cron()

 */

function mymodule_cron()  // mymodule will replace with module name

{

  // get all files ids

  $fids = Drupal::entityQuery('file')->execute();

  $file_usage = Drupal::service('file.usage');

  // loop all fids and load files by fid

  foreach ($fids as $fid) {

    $file = Drupal\file\Entity\File::load($fid);

    $usage = $file_usage->listUsage($file);

    // check if file not used

    if (count($usage) == 0) {

      $file->delete();

    }

  }

}


Note: If have any suggestions or issue regarding 'How to permanent delete unused files in Drupal 8?' then you can ask by comments. 

How to resolve max execution time error in drupal ?

When you found error regarding 'max_execution_time' exceed, then you can follow steps for resolve this error: Steps:   You can put t...