How to Parse a CSV File Using PHP

How to parse a CSV file using PHP

Just use the function for parsing a CSV file

http://php.net/manual/en/function.fgetcsv.php

$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}

parse CSV file in PHP by column

fgetcsv parses the given handle line by line (rows). It isn't possible to parse a csv file by column using core php. However, if you know the position of the 3 columns for which you wish to access the values, you could simply ignore all other columns:

 //position (zero indexed) of required columns
$columnsToProcess=[0,3,4]
for ($c=0; $c < $num; $c++) {
//do something with value if column's index is in the required columns array
if(in_array($c,$columnsToProcess)){
//value at position $c equals $data[$c]
echo $data[$c] . "<br />\n";
}
}

Moe info about fgetcsv : http://php.net/manual/en/function.fgetcsv.php

How to upload and parse a CSV file in php

Although you could easily find a tutorial how to handle file uploads with php, and there are functions (manual) to handle CSVs, I will post some code because just a few days ago I worked on a project, including a bit of code you could use...

HTML:

<table width="600">
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">

<tr>
<td width="20%">Select file</td>
<td width="80%"><input type="file" name="file" id="file" /></td>
</tr>

<tr>
<td>Submit</td>
<td><input type="submit" name="submit" /></td>
</tr>

</form>
</table>

PHP:

if ( isset($_POST["submit"]) ) {

if ( isset($_FILES["file"])) {

//if there was an error uploading the file
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";

}
else {
//Print file details
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

//if file already exists
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
}
else {
//Store file in directory "upload" with the name of "uploaded_file.txt"
$storagename = "uploaded_file.txt";
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $storagename);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"] . "<br />";
}
}
} else {
echo "No file selected <br />";
}
}

I know there must be an easier way to do this, but I read the CSV file and store the single cells of every record in an two dimensional array.

if ( isset($storagename) && $file = fopen( "upload/" . $storagename , r ) ) {

echo "File opened.<br />";

$firstline = fgets ($file, 4096 );
//Gets the number of fields, in CSV-files the names of the fields are mostly given in the first line
$num = strlen($firstline) - strlen(str_replace(";", "", $firstline));

//save the different fields of the firstline in an array called fields
$fields = array();
$fields = explode( ";", $firstline, ($num+1) );

$line = array();
$i = 0;

//CSV: one line is one record and the cells/fields are seperated by ";"
//so $dsatz is an two dimensional array saving the records like this: $dsatz[number of record][number of cell]
while ( $line[$i] = fgets ($file, 4096) ) {

$dsatz[$i] = array();
$dsatz[$i] = explode( ";", $line[$i], ($num+1) );

$i++;
}

echo "<table>";
echo "<tr>";
for ( $k = 0; $k != ($num+1); $k++ ) {
echo "<td>" . $fields[$k] . "</td>";
}
echo "</tr>";

foreach ($dsatz as $key => $number) {
//new table row for every record
echo "<tr>";
foreach ($number as $k => $content) {
//new table cell for every field of the record
echo "<td>" . $content . "</td>";
}
}

echo "</table>";
}

So I hope this will help, it is just a small snippet of code and I have not tested it, because I used it slightly different. The comments should explain everything.

Parse CSV file into columns using PHP

$newArray = [];

if (($fh = fopen("Book1.csv", "r")) !== FALSE) {
while (($data = fgetcsv($fh, 1000, ",")) !== FALSE) {
$o = new stdClass;

$o->MobileNumber = trim($data[0]);
$o->Carrier = trim($data[1]);
$o->ValidityStatus = trim($data[2]);
$newArray[$o->Carrier][] = $o;
}
}

Should produce an array of Carriers, each with an array of objects with phone number and statuses inside

How to parse a csv file that contains 15 million lines of data in php

Iterating over a large dataset (file lines, etc.) and pushing into array it increases memory usage and this is directly proportional to the number of items handling.
So the bigger file, the bigger memory usage - in this case.
If it's desired a function to formatting the CSV data before processing it, backing it on the of generators sounds like a great idea.

Reading the PHP doc it fits very well for your case (emphasis mine):

A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which
may cause you to exceed a memory limit, or require a considerable
amount of processing time to generate.

Something like this:



function csv_read($filename, $delimeter=',')
{
$header = [];
$row = 0;
# tip: dont do that every time calling csv_read(), pass handle as param instead ;)
$handle = fopen($filename, "r");

if ($handle === false) {
return false;
}

while (($data = fgetcsv($handle, 0, $delimeter)) !== false) {

if (0 == $row) {
$header = $data;
} else {
# on demand usage
yield array_combine($header, $data);
}

$row++;
}
fclose($handle);
}

And then:

$generator = csv_read('rdu-weather-history.csv', ';');

foreach ($generator as $item) {
do_something($item);
}

The major difference here is:
you do not get (from memory) and consume all data at once. You get items on demand (like a stream) and process it instead, one item at time. It has huge impact on memory usage.


P.S.: The CSV file above has taken from: https://data.townofcary.org/api/v2/catalog/datasets/rdu-weather-history/exports/csv

How to create an array from a CSV file using PHP and the fgetcsv function

Like you said in your title, fgetcsv is the way to go. It's pretty darn easy to use.

$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
print_r($line);
}
fclose($file);

You'll want to put more error checking in there in case fopen() fails, but this works to read a CSV file line by line and parse the line into an array.

How to extract data from csv file in PHP

You can use fgetcsv to parse a CSV file without having to worry about parsing it yourself.

Example from PHP Manual:

$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}

parse csv in cell with new line using php

function get2DArrayFromCsv($file,$delimiter) 
{
if (($handle = fopen($file, "r")) !== FALSE) {
$i = 0;
while (($lineArray = fgetcsv($handle, 10000, $delimiter)) !== FALSE) {
for ($j=0; $j<count($lineArray); $j++) {
$data2DArray[$i][$j] = $lineArray[$j];
}
$i++;
}
fclose($handle);
}
return $data2DArray;
}
$resList=get2DArrayFromCsv($csv_file, ',');

Can you let me know this will help you or not.

How to parse csv data and insert in database using php codeigniter

Just Converted .xlsx file to .csv file.

How to read .csv file row wise using PHP

Use the function fgetcsv().

// Read the first line, headers
$headers = fgetcsv($file);
// Now $headers is an array of your headers

// Read the lines one by one
while (false != ($line = fgetcsv($file))) {
// $line is an array of your cells
}


Related Topics



Leave a reply



Submit