I'm having a problem using a CSV file uploaded via a PHP form. Here is the code:
$row = 1;
if (($handle = fopen($_FILES['csv']['tmp_name'], "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);
}
The only problem is, when I'm interrogating the variable $data it appears the contents of the CSV file is written to one row, rather than multiple rows. As a result, I get an array of 228 column values.
Why is this? Is my PHP script not detecting a new line correctly? If so, is there an option to fix this behaviour?
set the auto_detect_line_endings ini setting to true:
ini_set('auto_detect_line_endings', true);
Most likely problem is the line endings in your source data. Could you make a test CSV file with several columns and rows to confirm or eliminate the data you're testing with?
See also: http://www.php.net/manual/en/filesystem.configuration.php#ini.auto-detect-line-endings
Related
I am importing a CSV file which contains list of URLS. These URLs are displaying in tabular format to perform some operations. But a space is added to the beginning of url. Because of this the operations I am performing on it fails. So how I can remove that space.When I done print_r() in my controller it shows result as
�https://www.surveygizmo.com
if (($handle = fopen($filename, "r")) !== FALSE)
{
while (($value = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$num = count($value);
for ($c=0; $c < $num; $c++)
{
echo "<pre>";
print_r($value[$c]);
Above a few lines of code. I am getting symbol,� before the content.
How can I remove that? I tried with trim. But still its not working. I need help. Thank you
Try this. I have similar issue and after following tweak it fixed
$col_val = $value[$c];
$final_value = trim($col_val ," \t\n\r\0\x0B\"");
print_r($final_value);
I am converting csv file to an array using code bellow. But, problem is that end of the row is CR LF, and it is not detected, so array has wrong offset. CR LF is ignored and "cells" around it are merged.
How could i rewrite code to detect this row ending and split array correctly ? Or, is there better approach to convert csv to array?
There are some simmilar questions here but i have not found solution to this issue yet.
Thanks.
$fileName ='test.csv';
$csvData = file_get_contents($fileName);
$csvNumColumns = 11;
$csvDelim = ";";
$data = array_chunk(str_getcsv($csvData, $csvDelim), $csvNumColumns);
print_r($data);
Have you tried using fgetcsv()? full info on php.net.
Example usage from php.net
<?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);
}
?>
I would avoid str_getcsv() and work with fgetcsv() to avoid dealing with some of the end of line futz.
http://php.net/manual/en/function.fgetcsv.php
if (($handle = fopen("fileName", "r")) !== FALSE) {
while (($data = fgetcsv($handle)) !== FALSE) {
var_dump($data); //array representation of one line of csv...
}
}
fclose($handle);
If you're on a Mac...
Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.
I am trying to read a CSV file (delimited by commas) but unfortunately, it isn't responding as it ought to. I am not so sure what I am doing wrong here, but I'll paste out the contents of the code and the CSV file both :
$row = 0;
if($handle = fopen("SampleQuizData.csv","r") !== FALSE)
{
// WORKS UNTIL HERE, SO FILE IS BEING READ
while(!feof(handle))
{
$line = fgetcsv($handle, 1024, ",") ;
echo $line[2]; // DOES NOT WORK
}
}
Here is the CSV file: (the emails and names have been changed here to protect the identities of the users)
parijat,something,parijatYkalia#hotmail.com
matthew,durp, mdurpdurp#gmail.com
steve,vai,stevevai#gmail.com
rajni,kanth,rajnikanth#superman.com
it lacks a '$' to the handle variable
while(!feof($handle)){
and not :
while(!feof(handle)){
Give this a try:
<?php
$row = 0;
if (($handle = fopen("SampleQuizData.csv", "r")) !== FALSE)
{
while(!feof($handle))
{
$line = fgetcsv($handle, 1024, ",") ;
echo "$line[2]";
}
}
?>
It's worth a mention but when I was working on CSV exports a few weeks ago, I had weird line ending inconsistencies. So I put this at the top of my php file and it worked splendid.
<?php
ini_set("auto_detect_line_endings", true);
?>
i know how to upload a csv file into mysql database but only through cmd. i want to know how to upload csv file into mysql database using php form and will disregard some information on the excel and will only start importing starting from a certain line. ? kindly help me.
(PHP 4, PHP 5)
fgetcsv
See php manual http://php.net/manual/en/function.fgetcsv.php
<?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);
}
?>
Try this it's working well, you can add as many values as possible depending on the number of columns you have in the CSV file. Then in the HTML code put the uploading syntax in the tag.
**
$fname = $_FILES['csv_file']['name'];
$chk_ext = explode(".",$fname);
$filename = $_FILES['csv_file']['tmp_ name'];
$handle = fopen($filename, "r");
if(!$handle){
die ('Cannot open file for reading');
}
while (($data = fgetcsv($handle, 10000, ",")) !== FALSE)
{
$query = "INSERT INTO tablename (col1_csv, col2_csv)
values ('$data[0]', '$data[1]');
mysql_query($query) or die(mysql_error ());
}
fclose($handle);
?>
**
You can use the MySQL LOAD DATA INFILE statement to bulk-insert thousands of records at once. PHP can handle the file upload. The PHP code would be something similar to:
$query = sprintf("
LOAD DATA LOCAL INFILE '%s'
INTO TABLE `table1`
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\\r\\n'
IGNORE 1 LINES
",
mysql_real_escape_string($FILES["file1"]["tmp_name"])
);
The LOCAL keyword should allow you to workaround some security restrictions. Change the FIELDS TERMINATED BY and LINES TERMINATED BY parameter to match the separators used by excel while exporting. IGNORE 1 LINES tells MySQL to skip the header row(s).
Note: Excel does not seem to use an escape character; but it will (i) enclose the fields that contain , and " with " (ii) use "" to escape a single " inside data. I believe MySQL will understand this encoding and import the data correctly.
You could use the "LOAD DATA INFILE " statement with the " IGNORE ... LINES " option which you can use from the command line as well as from PHP.
try this:
$filename=$_FILES["upload_file"]["name"];
$extension = end(explode(".",$filename));
if ($extension=='csv') {
$tmp_file=$_FILES["upload_file"]["tmp_name"];
$handle = #fopen($tmp_file, "r");
//specify your own database connection parameter
$db = new PDO('mysql:host=localhost;dbname=demo','user','password');
$stmt = $db->prepare("INSERT INTO writers (writer_name, writer_email) VALUES (?, ?)");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
$array=explode(",",$buffer);
$count=1;
foreach ($array as $value) {
$stmt->bindParam($count, $value);
$count++;
}
$stmt->execute();
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
$db = null;
echo "<p>Success</p>";
}
else {
$error="<p style='color:red;'>Invalid file type</p>";
}
Refer to http://pradipchitrakar.com.np/programming/upload-csv-mysql-php/
How do I import CSV files using zend framework? Should I use zend_file_transfer or is there any special class that I have to look into? Also if I use zend_file_transfer is there any special validator for CSV?
you don't have to use any zend libraries to import csv files, you can just use native php functions, take a look at fgetcsv
$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);
}
You could also use SplFileObject for reading CSV files.
From the php manual:
<?php
$file = new SplFileObject("animals.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
list($animal, $class, $legs) = $row;
printf("A %s is a %s with %d legs\n", $animal, $class, $legs);
}
?>
http://php.net/manual/en/splfileobject.fgetcsv.php
There is currently no way to do this with the Zend Framework. How can one be sure?
For example, Zend_Translate supports translation with CSV files, but if you check the the source code of the respective adapter (Zend_Translate_Adapter_Csv), you can verify it uses fgetcsv, and not a specific Zend class. Besides, this CSV adapter comes with the following warning:
Note: Beware that the Csv Adapter has
problems when your Csv files are
encoded differently than the locale
setting of your environment. This is
due to a Bug of PHP itself which will
not be fixed before PHP 6.0
(http://bugs.php.net/bug.php?id=38471).
So you should be aware that the Csv
Adapter due to PHP restrictions is not
locale aware.
which is related with the problems of the fgetcsv function.
Here's a function that reads a csv file and returns an array of items that contain the first two column data values.
This function could read a file of first_name,last_name for example.
function processFile ($filename) {
$rtn = array();
if (($handle = fopen($filename, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$item = array();
$item[] = $data[0];
$item[] = $data[1];
$rtn[] = $item;
}
}
return $rtn;
}