Read TXT file with PHP and write to mysql

Asked

Viewed 711 times

1

I am developing an application to control the equipment of the company, I can generate a log of the equipment with all the information related to the equipment, however this file is not tabulated, example below some lines:

SET SYS:SYSDESC="SQL01ALD", SYSOBJECTID="SQL01ALD", SYSSERVICES="UMTS";
ADD URNCBASIC:SQLID=490, NSAP="H'450551310008501F000000000000000000000000";
ADD UCNOPERATOR:CNOPINDEX=0, MCC="724", MNC="31", OPERATORTYPE=PRIM;
ADD OPC:SPX=0, SPDF=WNF, SPC=16360, NAME="SQL01ALD";
ADD N7DPC:DPX=1, SPDF=WNF, NAME="MSS68ALD", DPCT=IUCS_RANAP;
ADD N7DPC:DPX=2, SPDF=WNF, NAME="MGW04ALD", DPCT=IUCS_ALCAP;
ADD N7DPC:DPX=3, SPDF=WNF, NAME="SQL01ALD";
ADD N7DPC:DPX=4, SPDF=WNF, NAME="SQL01FLZ";
ADD N7DPC:DPX=5, SPDF=WNF, NAME="SQL02ALD";

The basic intention is to take a field as a reference, for example the field SYSDESC="SQL01ALD" copy only the SQL01ALD to the database.

For the logic of recording in the database, I thought I’d loop with while taking the file and recording in mysql.

The X of the question is how to take the field I want.

  • 3

    From what I understand he wants to translate data from a string(txt) into variables in PHP, and then insert it into his database. I see nothing wrong with the question and it is a problem that most of us have encountered before. What I don’t really understand is the absurd amount of -4 downvotes and no comment or help to the OP. Although I believe that the possibilities are broad and is duplicate, still can to solve the problem reasonably and there is no need to motivate the user to nay ask more questions because the community does not accept them. I gave an upvote to balance.

  • You’ll have to roll with the function fscanf and perhaps regular expressions :)

  • I would start by breaking by comma and then use regular expression

1 answer

1


$file = 'file.txt';

$resource = fopen($file, 'r');

$lines = '';
while(!feof($resource)){
    $lines[] = fgets($resource, 4096);
}

$fullVar = true;
$fullVar = $fullVar ? ':' : ''; 

$er = '~([\w%s]+)=("[^"]+"|\w+)~';

$varsFile = array();
foreach ($lines as $k => $value) {
    preg_match_all(sprintf($er, $fullVar), $value, $match);
    foreach ($match[1] as $kk => $result) {
        $varsFile[$k][$match[1][$kk]] = trim($match[2][$kk], '"');
    }
}

// AQUI VOCE TERA AS VARIAZEIS DE CADA LINHA
foreach ($varsFile as $linha => $vars){
    # code...
}

If you want to include all the variable name just keep $fullVar as true, otherwise changes to false that it will capture the reduced variable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.