Import, analyze and extract data from a CSV with PHP [closed]

6

How can I do to import a csv file with PHP and grab the data from a specific column and write that data to the database? Can you do this analysis and save only specific data (type a column, or row)?

    
asked by marcelmaino 17.03.2016 в 14:48

1 answer

8

To perform the process of reading a csv file in php is quite simple, since it is understood as a simple txt file that performs its separation using ; , so you could use functions like fopen to be able to open it , scroll and save in a variable.

Reading Example:

function getCSV($name) {
   $file = fopen($name, "r");
   $result = array();
   $i = 0;
   while (!feof($file)):
      if (substr(($result[$i] = fgets($file)), 0, 10) !== ';;;;;;;;') :
         $i++;
      endif;
   endwhile;
   fclose($file);
   return $result;
}

$foo = getCSV('foo.csv');

Normal reading right? just added a detail, that if inside the loop is to prevent a bug that happens in some versions of excel, this, and when you perform a scroll in the columns, these columns blank receive the; without exactly having a value. then in the end you end up saving an array with "junk".

Now that you have an array with everything! you can pick up the line by performing a simple explode.

Example Reading row by line:

function getLine($array, $index) {
   return explode(';', $array[$index]);
}

var_dump(getLine($foo, 0));

So if I have a spreadsheet like this:

Callingthefunctionwillhaveanarraylikethis:

Andtoreadfieldbyfieldofthislineyoucansavetoavariableandaccessthespecificindex:

$bar=getLine($foo,0);var_dump($bar[0]);

Inthiscasepickingupthefirstcolumn,youcanautomateloopingtogobyrecordingfieldbyfield.

Anexamplegenericinsertcouldbe:

$con=mysqli_connect("localhost", "my_user", "my_password", "my_db");
if (mysqli_connect_errno()) {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con, 'INSERT INTO Persons (foo,bar) VALUES (' . $bar[0] . ',' . $bar[1] . ')');
mysqli_close($con);

You can also read this file in javascript. if you want to do an initial validation of some field before uploading to your base and actually starting the import, this can generate a lot of server performance savings and high feedback to the user.

You have a solution using FileReader.

Example:

var leitorDeCSV = new FileReader();

window.onload = function init() {
  leitorDeCSV.onload = leCSV;
}

function pegaCSV(inputFile) {
  var file = inputFile.files[0];
  leitorDeCSV.readAsText(file);
}

function leCSV(evt) {

  var fileArr = evt.target.result.split('\n');
  var strDiv = '<table>';

  for (var i = 0; i < fileArr.length; i++) {
    strDiv += '<tr>';
    var fileLine = fileArr[i].split(',');
    for (var j = 0; j < fileLine.length; j++) {
      strDiv += '<td>' + fileLine[j].trim() + '</td>';
    }
    strDiv += '</tr>';
  }

  strDiv += '</table>';

  var CSVsaida = document.getElementById('CSVsaida');
  CSVsaida.innerHTML = strDiv;
}
<input type="file" id="inputCSV" onchange="pegaCSV(this)">
<div id="CSVsaida"></div>
    
17.03.2016 в 15:34
___ ___ erkimt Is there a difference between using "return" or "exit ()" to end the "main ()"? ______ qstntxt ___

%code% terminates running the application immediately. The %code% command exits the function, but when it is inside the %code% it will exit the application, including the value used in it will be returned to the one who called the application as an error code (zero is ok), as well as the function output.

Of course there is a difference in other functions, where %code% terminates application immediately and the command will return the execution stream to the calling function.

If both do the same thing in the described situation, does either use one or the other?

    
______ azszpr174313 ___

There is an important semantic difference in C ++. The %code% will close the scope and call all pending destructors. If the application is closed, rarely will the call of the destructors produce a different result, but technically it is possible for one of them to do something that is important to the end of the application, or to print relevant information for the user. >

Even though the action looks the same, the %code% function causes a premature exiting of the application. Then execution is terminated almost immediately. %code% finalizes static objects, but not destructors. The %code% and %code% neither does this and it closes on time.

There's a difference even in C if you have functions registered with %code% . These functions will always run no matter how the application is shutting down. But there will be undefined behavior if one of the linked functions in %code% has reference to some data in stack . Something like %code% and %code% . This is especially important in C. documentation

Note that the %code% function is not special and can be called within the application. In this case there will be an important difference since a %code% will not terminate the application, although in the context of the question this would not happen. But understand that if what you wrote will not be called in the operating system and this %code% is part of a module that will be loaded and used in another application, your module will terminate the application and not only your code if you use %code% , %code% will then be the most appropriate in most situations.

A call to %code% can be recursive, although it should not. Of course there is difference in this case, but it falls into what I said in the previous paragraph.

That's why you always have to choose the most semantically correct way . If you want to terminate the application immediately use %code% , otherwise use %code% . Many people say that if %code% is terminating the application, %code% is the most appropriate. Not everyone agrees, especially in C ++. That's why it's good to understand the workings, the implications of each and do not blindly follow rules.

I do not know if it counts as a difference, because it is a function, to use it, you need to use a %code% so that it is available, and if the code unit it contains would not enter the application, the executable will be a bit bigger. The command is always available.

    
___ Methods "__" or "Dunder" in Python, which are the most used?