Jump to content
  • Revista PROGRAMAR: Já está disponível a edição #60 da revista programar. Faz já o download aqui!

diokhan

ler ficheiros

Recommended Posts

diokhan

boas,

eu agora ando com uma nova tarefas em maos, tenho que ler um ficheiro e procurar por determinadas palavras, e guardar o valor que provem do ficheiro num array, e ao chegar ao fim do ficheiro inserir o array na base de dados.

por exemplo,

ficheiro:

region

{

name            = 1;

totalRawWells    = 919687;

totalKeyPass    = 911896;

key

{

keySequence              = CATG;

numKeyPass                = 6914;

numDotFailed              = 93;

numMixedFailed            = 115;

numTrimmedTooShortQuality = 984;

numTrimmedTooShortPrimer  = 0;

totalPassedFiltering      = 5722;

}

eu procuro por "region" e depois preciso guardar os valores de "name", "totalRawWells", e assim em array e no fim guardar na base de dados.

sei que preciso de usar o fgets para ler linha a linha, mas nao sei procurar as palavras que quero e guardar no array

agradeço toda a ajuda :P


...Join the dark side...and get a free cookie...

Share this post


Link to post
Share on other sites
diokhan

os ficheiros tem sempre a mesma estrutura, não muda, eu pensei usar o fgets para ler linha a linha e procurar pelas palavras que quero


...Join the dark side...and get a free cookie...

Share this post


Link to post
Share on other sites
KiNgPiTo

Acho que a maneira mais fácil já que a estrutura não muda é ler linha a linha e procurar na linha a palavra que queres... E se tiver, adicionas ao array uma substr da linha entre o strpos do = e do ;

Share this post


Link to post
Share on other sites
diokhan

e como posso fazer isso? que eu não sei por onde começar 🤔


...Join the dark side...and get a free cookie...

Share this post


Link to post
Share on other sites
diokhan

o ficheiro é assim, a estrutura é sempre igual:

region

{

name            = 1;

totalRawWells    = 919687;

totalKeyPass    = 911896;

key

{

keySequence              = CATG;

numKeyPass                = 6914;

numDotFailed              = 93;

numMixedFailed            = 115;

numTrimmedTooShortQuality = 984;

numTrimmedTooShortPrimer  = 0;

totalPassedFiltering      = 5722;

}

key

{

keySequence              = TCAG;

numKeyPass                = 904982;

numDotFailed              = 68338;

numMixedFailed            = 24450;

numTrimmedTooShortQuality = 328492;

numTrimmedTooShortPrimer  = 525;

totalPassedFiltering      = 483177;

}

}

e eu tenho assim o código:

<?php
$variable = array();
if($f = fopen('./454QualityFilterMetrics.txt', 'r')){
	$bFindRegion = 0;
	do 
	{
		$line = fgets($f);
		$pos = strpos($line, "region");
		if ((!($pos === false) && $pos == 0)){
		$bFindRegion = 1;
	}
	// name
		$pos = strpos($line, "name");
		if ($bFindRegion && (!($pos === false) && $pos == 1)){
			$pieces = explode ("=",$line);
			$piece = explode(";",$pieces[1]);
			$variable['name'] = $piece[0];
			echo $variable['name'];
		}
	// total raw wells
		$pos = strpos($line, "totalRawWells");
		if ($bFindRegion && (!($pos === false) && $pos == 1)){
			$pieces = explode ("=",$line);
			$piece = explode(";",$pieces[1]);
			$variable['totalRawWells'] = $piece[0];
			echo $variable['totalRawWells'];
		}
	// total key pass
		$pos = strpos($line, "totalKeyPass");
		if ($bFindRegion && (!($pos === false) && $pos == 1)){
			$pieces = explode ("=",$line);
			$piece = explode(";",$pieces[1]);
			$variable['totalKeyPass'] = $piece[0];
			echo $variable['totalKeyPass'];
			echo "<br>";
		}

	// key sequence
		$pos = strpos($line, "keySequence");
		if ($bFindRegion && (!($pos === false) && $pos == 2)){
			$pieces = explode ("=",$line);
			$piece = explode(";",$pieces[1]);
			$variable['keySequence'] = $piece[0];
			echo $variable['keySequence'];
		}
	// num Key Pass
		$pos = strpos($line, "numKeyPass");
		if ($bFindRegion && (!($pos === false) && $pos == 2)){
			$pieces = explode ("=",$line);
			$piece = explode(";",$pieces[1]);
			$variable['numKeyPass'] = $piece[0];
			echo $variable['numKeyPass'];
		}
	// num Dot Failed
		$pos = strpos($line, "numDotFailed");
		if ($bFindRegion && (!($pos === false) && $pos == 2)){
			$pieces = explode ("=",$line);
			$piece = explode(";",$pieces[1]);
			$variable['numDotFailed'] = $piece[0];
			echo $variable['numDotFailed'];
		}
	// num Mixed Failed
		$pos = strpos($line, "numMixedFailed");
		if ($bFindRegion && (!($pos === false) && $pos == 2)){
			$pieces = explode ("=",$line);
			$piece = explode(";",$pieces[1]);
			$variable['numMixedFailed'] = $piece[0];
			echo $variable['numMixedFailed'];
		}	
	//num Trimmed Too Short Quality
		$pos = strpos($line, "numTrimmedTooShortQuality");
		if ($bFindRegion && (!($pos === false) && $pos == 2)){
			$pieces = explode ("=",$line);
			$piece = explode(";",$pieces[1]);
			$variable['numTrimmedTooShortQuality'] = $piece[0];
			echo $variable['numTrimmedTooShortQuality'];
		}	
	// num Trimmed Too Short Primer
		$pos = strpos($line, "numTrimmedTooShortPrimer");
		if ($bFindRegion && (!($pos === false) && $pos == 2)){
			$pieces = explode ("=",$line);
			$piece = explode(";",$pieces[1]);
			$variable['numTrimmedTooShortPrimer'] = $piece[0];
			echo $variable['numTrimmedTooShortPrimer'];
		}	
	// total Passed Filtering
		$pos = strpos($line, "totalPassedFiltering");
		if ($bFindRegion && (!($pos === false) && $pos == 2)){
			$pieces = explode ("=",$line);
			$piece = explode(";",$pieces[1]);
			$variable['totalPassedFiltering'] = $piece[0];
			echo $variable['totalPassedFiltering'];
			echo "<br>";
		}
	} while (!feof($f));
	fclose($f);

	}else{
		echo 'failure';
}
?>

mas só devolve 3 valores, o name, totalRawWells, totalKeyPass. os outros como são dados que são duplicados eles não devolve. como posso resolver este problema?

ja esta arranjado, agora falta-me inserir na base de dados


...Join the dark side...and get a free cookie...

Share this post


Link to post
Share on other sites
diokhan

agora por exemplo, eu alterei o sistema que usei, agora tenho um ficheiro que pede ao utilizador o ficheiro para ler, depois tenho um ficheiro que lê os dados e tenho outro que trata os dados para inserir na base de dados, como posso fazer para passar de um lado para o outro? neste momento tenho assim:

readQuality.php

<?php
echo "<form method='POST' action='#' enctype='multipart/form-data'>
	<input type='file' name='uploaded'><br>
	<input type='submit' value='Upload file'><br>";
echo "</form>";
require_once("./qualityRead.php");
?>

qualityRead.php

<?php
$variable = array();

//if($f = fopen("./../454QualityFilterMetrics.txt", 'r')){
if ($f = fopen($uploaded, 'r')){
	$bFindRegion = 0;
	do 
	{
		$line = fgets($f);
		$pos = strpos($line, "region");
		if ((!($pos === false) && $pos == 0))
		{
			$bFindRegion = 1;
		}
	// name
		$pos = strpos($line, "name");
		if ($bFindRegion && (!($pos === false) && $pos == 1)){
			$pieces = explode ("=",$line);
			$piece = explode(";",$pieces[1]);
			$variable['name'] = $piece[0];
			echo $variable['name'];
		}
	// total raw wells
		$pos = strpos($line, "totalRawWells");
		if ($bFindRegion && (!($pos === false) && $pos == 1)){
			$pieces = explode ("=",$line);
			$piece = explode(";",$pieces[1]);
			$variable['totalRawWells'] = $piece[0];
			echo $variable['totalRawWells'];
		}
	// total key pass
		$pos = strpos($line, "totalKeyPass");
		if ($bFindRegion && (!($pos === false) && $pos == 1)){
			$pieces = explode ("=",$line);
			$piece = explode(";",$pieces[1]);
			$variable['totalKeyPass'] = $piece[0];
			echo $variable['totalKeyPass'];
			echo "<br>";
		}

	// key sequence
		$pos = strpos($line, "keySequence");
		if ($bFindRegion && (!($pos === false) && $pos == 2)){
			$pieces = explode ("=",$line);
			$piece = explode(";",$pieces[1]);
			$variable['keySequence'] = $piece[0];
			echo $variable['keySequence'];
		}
	// num Key Pass
		$pos = strpos($line, "numKeyPass");
		if ($bFindRegion && (!($pos === false) && $pos == 2)){
			$pieces = explode ("=",$line);
			$piece = explode(";",$pieces[1]);
			$variable['numKeyPass'] = $piece[0];
			echo $variable['numKeyPass'];
		}
	// num Dot Failed
		$pos = strpos($line, "numDotFailed");
		if ($bFindRegion && (!($pos === false) && $pos == 2)){
			$pieces = explode ("=",$line);
			$piece = explode(";",$pieces[1]);
			$variable['numDotFailed'] = $piece[0];
			echo $variable['numDotFailed'];
		}
	// num Mixed Failed
		$pos = strpos($line, "numMixedFailed");
		if ($bFindRegion && (!($pos === false) && $pos == 2)){
			$pieces = explode ("=",$line);
			$piece = explode(";",$pieces[1]);
			$variable['numMixedFailed'] = $piece[0];
			echo $variable['numMixedFailed'];
		}	
	//num Trimmed Too Short Quality
		$pos = strpos($line, "numTrimmedTooShortQuality");
		if ($bFindRegion && (!($pos === false) && $pos == 2)){
			$pieces = explode ("=",$line);
			$piece = explode(";",$pieces[1]);
			$variable['numTrimmedTooShortQuality'] = $piece[0];
			echo $variable['numTrimmedTooShortQuality'];
		}	
	// num Trimmed Too Short Primer
		$pos = strpos($line, "numTrimmedTooShortPrimer");
		if ($bFindRegion && (!($pos === false) && $pos == 2)){
			$pieces = explode ("=",$line);
			$piece = explode(";",$pieces[1]);
			$variable['numTrimmedTooShortPrimer'] = $piece[0];
			echo $variable['numTrimmedTooShortPrimer'];
		}	
	// total Passed Filtering
		$pos = strpos($line, "totalPassedFiltering");
		if ($bFindRegion && (!($pos === false) && $pos == 2))
		{
			$pieces = explode ("=",$line);
			$piece = explode(";",$pieces[1]);
			$variable['totalPassedFiltering'] = $piece[0];
			echo $variable['totalPassedFiltering'];
			echo "<br>";
			require_once ('./../functions.php');
			$quality = new Quality;

			$quality->SetNameQuality($variable['name']);
			$quality->SetQualityRawWells($variable['totalRawWells']);
			$quality->SetQualityTotalKeyPass($variable['totalKeyPass']);
			$quality->SetKeyPass($variable['numKeyPass']);
			$quality->SetDotFailed($variable['numDotFailed']);
			$quality->SetMixedFailed($variable['numMixedFailed']);
			$quality->SetShortQuality($variable['numTrimmedTooShortQuality']);
			$quality->SetPrimerFailed($variable['numTrimmedTooShortPrimer']);
			$quality->SetPassedFilter($variable['totalPassedFiltering']);
			$quality->SetControlLibrary($variable['keySequence']);

			$error = $quality->insertQuality();
			if(!empty($error['2']))
			{
				echo $error['2'];
			}
		}

	} while (!feof($f));
		fclose($f);

	}else{
		//echo 'failure';
}
?>

e tenho estas duas funções, uma verifica se já existe e a outra insere ou actualiza o que já existe:

function verifyQuality($name, $keySequence)
	{
		try 
		{	
			$sql = "SELECT P.NAME_PROJECT, Q.REGION FROM QUALITY_PROJECT AS QP
						Inner Join quality AS Q ON Q.ID_QUALITY = QP.ID_QUALITY
						Inner Join project AS P ON P.ID_PROJECT = QP.ID_PROJECT
						WHERE Q.REGION = $name AND Q.CONTROL_LIBRARY = $keySequence";
			$stmt = $this->dbh->prepare($sql);
			$stmt->execute();
		} catch (PDOException $e) {
        	return -1;
            echo 'Query error: ' . $e->getMessage();
    	}
    	$count = $stmt->fetchColumn();
        $stmt->closeCursor(); 
        
        if($count > 0 ){
        	return 1;
        }else{
        	return 0;
        }
	}

	function insertQuality()
	{
		$verQual = new Quality;
		$verQual->verifyQuality($this->NameQuality, $this->ControlLibrary);

		/*echo $this->NameQuality." - ";
		echo $this->PassedFilter." - ";
		echo $this->ControlLibrary."<br>";*/

		if ($verQual == 1){ //se ja existe UPDATE

			$stmt = $this->dbh->prepare("UPDATE QUALITY SET REGION = :name, RAW_WELLS = :rawWells,
											TOTAL_KEYPASS = :totalKeyPass, KEYPASS = :keyPass,
											DOT_FAILED = :dotFailed, MIXED_FAILED = :mixedFailed,
											SHORT_QUALITY = :shortQuality, PRIMER_FAILED = :primerFailed,
											PASSED_FILTER = :passedFilter, CONTROL_LIBRARY = :controlLibrary");
			$stmt->bindParam(':name', $this->NameQuality);
			$stmt->bindParam(':rawWells', $this->QualityRawWells);
			$stmt->bindParam(':totalKeyPass', $this->QualityTotalKeyPass);
			$stmt->bindParam(':keyPass', $this->KeyPass);
			$stmt->bindParam(':dotFailed', $this->DotFailed);
			$stmt->bindParam(':mixedFailed', $this->MixedFailed);
			$stmt->bindParam(':shortQuality', $this->ShortQuality);
			$stmt->bindParam(':primerFailed', $this->PrimerFailed);
			$stmt->bindParam(':passedFilter', $this->PassedFilter);
			$stmt->bindParam(':controlLibrary', $this->ControlLibrary);
			$stmt->execute();

		}elseif ($verQaul == 0){ // se nao existe INSERT

			// INSERT INTO QUALITY
			$stmt = $this->dbh->prepare("INSERT INTO QUALITY (REGION,RAW_WELLS,TOTAL_KEYPASS,KEYPASS,
											DOT_FAILED,MIXED_FAILED,SHORT_QUALITY,PRIMER_FAILED,
											PASSED_FILTER,CONTROL_LIBRARY) VALUES (:name, :rawWells,
											:totalKeyPass, :keyPass, :dotFailed, :mixedFailed, :shortQuality,
											:primerFailed, :passedFilter, :controlLibrary)");
			try{
				$stmt->bindParam(':name', $this->NameQuality);
				$stmt->bindParam(':rawWells', $this->QualityRawWells);
				$stmt->bindParam(':totalKeyPass', $this->QualityTotalKeyPass);
				$stmt->bindParam(':keyPass', $this->KeyPass);
				$stmt->bindParam(':dotFailed', $this->DotFailed);
				$stmt->bindParam(':mixedFailed', $this->MixedFailed);
				$stmt->bindParam(':shortQuality', $this->ShortQuality);
				$stmt->bindParam(':primerFailed', $this->PrimerFailed);
				$stmt->bindParam(':passedFilter', $this->PassedFilter);
				$stmt->bindParam(':controlLibrary', $this->ControlLibrary);
				$stmt->execute();

			}catch(PDOException $e) 
			{
			    echo 'Query error: ' . $e->getMessage();
			}
			// INSERT INTO QUALITY_PROJECT
				/*$stmt2 = $this->dbh->prepare("INSERT INTO QUALITY_PROJECT (ID_QUALITY, ID_PROJECT) 
												VALUES (:idQuality, :idProject)");
				try{
					$stmt2->bindParam(':idQuality');
					$stmt2->bindParam(':idProject');
				}catch(PDOException $e) 
			{
			    echo 'Query error: ' . $e->getMessage();
			}*/
		}
	}


...Join the dark side...and get a free cookie...

Share this post


Link to post
Share on other sites
diokhan

eu dividi em 3 ficheiros para não ser um muito grande, mas eu ando a modificar ainda e assim, não é o código final


...Join the dark side...and get a free cookie...

Share this post


Link to post
Share on other sites
KiNgPiTo

No form, adiciona hiddens inputs com o value igual ao elemento do array que quiseres... passa pelo post para o teu script e adicionas à BD...

Share this post


Link to post
Share on other sites
diokhan

No form, adiciona hiddens inputs com o value igual ao elemento do array que quiseres... passa pelo post para o teu script e adicionas à BD...

mas como eu estou em ficheiros separados não há problema? 🤔


...Join the dark side...and get a free cookie...

Share this post


Link to post
Share on other sites
diokhan

actualizei o meu código, já esta a passar os valores, mas ainda não insere na base de dados 🤔


...Join the dark side...and get a free cookie...

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.