CSV Parser

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN” “http://www.w3.org/TR/html4/strict.dtd”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<title>Data Import</title>
</head>

<body>

<?php

//error_reporting(E_ALL);
//ini_set(“display_errors”, 1);

$databasehost = “xxxxx”;
$databasename = “xxxxx”;
$databasetable = “xxxxxx”;
$databaseusername =”xxxxxx”;
$databasepassword = “xxxxxx”;
$fieldseparator = “\t”;
$lineseparator = “\r”;
$csvfile = “xxxxxx.txt”;
echo “vars set — “;
$addauto = 0;

$save = 0;
$outputfile = “output.sql”;

if(!file_exists($csvfile)) {
echo “File not found. Make sure you specified the correct path.\n”;
exit;
} else {
echo “$csvfile File Exist….<br />”;
}

echo “opening file<br />”;
$file = fopen($csvfile,”r”);

if(!$file) {
echo “Error opening data file.\n”;
die(“oops!”);
} else {
echo “file opened…<br />”;
}

$size = filesize($csvfile);

if(!$size) {
echo “File is empty.\n”;
exit;
} else {
echo “File Size is $size”;
}
echo “about to read…”;

if (!$csvcontent = fread($file,$size)) {

die(“Could Not Read File <br />”);

} else {

echo “File Read <br />”;

}

fclose($file);

if (isset($_GET[‘import’])) {

//$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
//mysql_select_db($databasename) or die(mysql_error());

$lines = 0;
$queries = “”;
$linearray = array();

foreach(split($lineseparator,$csvcontent) as $line) {

$lines++;

$line = trim($line,” \t”);

$line = str_replace(“\r”,””,$line);

$line = str_replace(“‘”,”\'”,$line);

$line = str_replace(“\””,””,$line);

$linearray = explode($fieldseparator,$line);

$linemysql = implode(“|”,$linearray);
//echo “$linemysql<br /><br />”;
$fields = explode(“|”,$linemysql);
print_r($fields);

echo “<br /><br />”;

$query = “INSERT INTO $databasetable (xxxxxx,xxxxxx,xxxxxx) VALUES (‘$linemysql’);”;

//echo “$query — $lines — <br /><br />”;

//mysql_query($query);

}

} // end if is set GET_

mysql_close($con);

?>

</body>
</html>

LEAVE A REPLY

Please enter your comment!
Please enter your name here

*