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;
}
Related
I have an issue in my php script which I don't understand. I know there are several questions regarding this issue but none fits to my issue.
I actually have one input file delimited by tabulation named testfile.txt.
With this txt file, I create a new file named result.txt where I take content of testfile in column 0 and column 7.
When I execute my php script, I get this error:
Notice: Undefined offset: 7
The thing that I don't understand is, my result.txt is well created with data contained in my column 0 and 7 from my testfile.txt. If I do:
echo $dataFromTestFile[7];
I have in output contents in column 7.
So I don't really understand why I have this notice and how to remove it.
Here's my php script:
<?php
if (false !== ($ih = fopen('/opt/lampp/htdocs/ngs/tmp/testfile.txt', 'r'))) {
$oh = fopen('/opt/lampp/htdocs/ngs/tmp/result.txt', 'w');
while (false !== ($dataFromTestFile = fgetcsv($ih,0,"\t"))) {
// this is where I build my new row
$outputData = array($dataFromTestFile[0], $dataFromTestFile[7]);
fputcsv($oh, $outputData);
//echo $dataFromTestFile[7];
}
fclose($ih);
fclose($oh);
}
?>
Sample data of testfile.txt:
Input Errors AccNo Genesymbol Variant Reference Coding Descr. Coding
aaa ddd fdfd dfdf fefefd ref1 fdfdfd fdfdf dfdfde
I suspect this is the line that's causing the error:
$outputData = array($dataFromTestFile[0], $dataFromTestFile[7]);
You are trying to use array elements at specific index without checking if they actually exists.
Also, you are trying to write an array object to the result file, did you mean to create a comma separated value in that file?
Try this:
$source = '/opt/lampp/htdocs/ngs/tmp/testfile.txt';
$result = '/opt/lampp/htdocs/ngs/tmp/result.txt';
if (($handle = fopen($source, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
if (isset($data[0]) && isset($data[7])) {
file_put_contents($result, $data[0] .','. $data[7] ."\r\n");
}
}
fclose($handle);
}
Alternatively, you could write the result as a csv like this also:
$sourceFile = '/opt/lampp/htdocs/ngs/tmp/testfile.txt';
$resultFile = '/opt/lampp/htdocs/ngs/tmp/result.txt';
$resultData = array();
// Parse source file
if (($handle = fopen($sourceFile, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
if (isset($data[0]) && isset($data[7])) {
$resultData[] = array($data[0], $data[7]);
}
}
fclose($handle);
}
// Write result file
if (sizeof($resultData)) {
$h = #fopen($resultFile, 'w');
if (!$h) {
exit('Failed to open result file for writing.');
}
foreach ($resultData as $resultRow) {
fputcsv($h, $resultRow, ',', '"');
}
fclose($h);
}
make sure the column 7 exists in your testfile.txt - i guess when starting from zero it may be column number 6 - also you can
var_dump($dataFromTestFile)
in order to get the content of the variable - array keys and values might be of interest for your issue
I have a large CSV I am writing a PHP CLI script to import into an existing PHP application, while utilizing the existing application's ORM to do relationship management between fields (trust me, I looked at a SQL CSV import, its easier this way). The issue at hand is that the CSV data I have is either malformed, or I have my fgetcsv() call wrong.
This is an example data set i'm aiming to import:
id,fname,lname,email\n
1,John,Public,johnqpublic#mailinator.com\n
1,Jane,Public,janeqpublic#mailinator.com\n
And the CSV Import code pretty much takes from the PHP Docs on fgetcsv():
function import_users($filepath) {
$row = 0;
$linesExecuted = 0;
if(($file = fopen($filepath, 'r')) !== false) {
$header = fgetcsv($file); //Loads line 1
while(($data = fgetcsv($file, 0, ",")) !== false) {
$userObj = user_record_generate_stdclass($data);
//A future method actually pipes the data through via the ORM
$row++;
}
fclose($file);
} else {
echo "It's going horribly wrong";
}
echo $row." records imported.";
}
The resulting logic of this method is pretty much a % sign, which is baffling. Am I overlooking something?
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've looked for questions on this topic, but failed to get what I'm looking for. This is for C++, I need similar for PHP. This is for including php files, I just want to read a CSV file.
I have this:
if(file_exists("data.csv")){
echo "CSV file found";
$csv_data = file_get_contents("data.csv");
$lines = explode("\n", trim($csv_data));
$array = array();
foreach ($lines as $line){
$array[] = str_getcsv($line);
}else {echo "File not found";}
But I want to NOT specify the file name - i.e. generically load/read/open the file.
Is there any simple why of doing that? Doesn't make sense, but I was told to not have anything hard coded in my PHP script.
Thanks in advance.
use fgetcsv
if(file_exists("data.csv")){
echo "CSV file found";
$handle = fopen("data.csv", "r");
if(!$handle) die("Could not open file!");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}else {echo "File not found";}
If you may not have anything hard coded in your script, you need to put those hardcoded things into some sort of external config file. You will have to hardcode the name of that config file into your bootstrap or whatever comes first in your application. Once the config is loaded, make the configuration data available in the places where it is needed. Not hardcoding configuration data into your code will allow you to create more reusable components and code, e.g. CSV Reader that can read any CSV file instead of a CSV Reader that can only read that one particular CSV file hardcoded into it.
Example:
// config.php
<?php
return array(
'csvFile' => '/path/to/file.csv',
…
);
// bootstrap.php
<?php
$config = include '/path/to/config.php';
…
// someFile.php
<?php
include '/path/to/bootstrap.php';
$file = new SplFileObject($config['csvFile']);
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
// Do something with values
}
Put your code into a function...
function open_file($file_name)
{
if (!file_exists($file_name))
{
return false;
}
$csv_data = file_get_contents($file_name);
$lines = explode("\n", trim($csv_data));
$array = array();
foreach ($lines as $line)
{
$array[] = str_getcsv($line);
}
return $array;
}
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);
?>