How to read fasta sequences from a file using PHP?

in Algorithms/Bioinformatics Programming/Fasta by

Here is a simple function in PHP to read fasta sequences from a file.

Your multifasta input file is “input.fasta”.

 

function read_fastas($filename){

  $fh = fopen($filename, 'r');
  $i= 0 ;
 
 $sequences = array();
  while($line = fgets($fh)){
    $i++;
    if($i%2==1){
      $sequence['header'] = $line;
    }
    else{
     $sequence['sequence'] = $line;
     array_push($sequences, $sequence);
    }

  }

 return $sequences;

}

The rest of the script would go like this:

<?php
$filename = "input.fasta";

//Define function
function read_fastas($filename){

  $fh = fopen($filename, 'r');
  if (filesize($x) == 0) { //check if file is empty or not
    echo "Input file is empty!";
  }
  else{
  $i= 0 ;
 
 $sequences = array();
  while($line = fgets($fh)){
    $i++;
    if($i%2==1){
      $sequence['header'] = $line;
    }
    else{
     $sequence['sequence'] = $line;
     array_push($sequences, $sequence);
    }

  }

 return $sequences;
}
}

//Call the function
read_fastas();
//do something with your fasta
?>

 

Download PDF

Tariq's areas of expertise include algorithm design, phylogenetics, MicroArray, Plant Systematics and genome data analysis. He is looking for a suitable PhD position in Bioinformatics. If you want him in your lab, let him know here

Leave a Reply