Parsing a CSV File - php
i am trying to convert my xls file into csv and parse it in php
Here is sampled converted cvs Windows conversion separated by commas
DFRWR2496W/BND*,,2.65 ,2.52 ,3.98 ,910,856,1126,
DFWR0006-RD.50W,,2.43 ,2.31 ,3.65 ,380,331,578,
DFWR0006-RD.75W,,3.50 ,3.33 ,5.25 ,490,419,775,
DFWR0006-RD1.0W,,4.44 ,4.22 ,6.66 ,610,520,972,
IN Php i am trying to pase the xxxx.csv file as
$file_handle = fopen("price.csv", 'r');
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle, 1024,"\r");
}
fclose($file_handle);
return $line_of_text[0];
However $line_of_text[0] is giving me
["DFRWR2496W\/BND*,,2.65,2.52,3.98,910,856,1126","DFWR0006-RD.50W,,2.43,2.31,3.65,380,331,578","DFWR0006-RD.75W,,3.5,3.33,5.25,490,419,775","DFWR0006-RD1.0W,,4.44,4.22,6.66,610,520,972","DFWR0006-RD1.0Y,,4.44,4.22,6.66,610,520,972","DFWR0006W\/BND,,2.47,2.35,3.71,385,335,586","DFWR0007-RD.50W,,4.54,4.31,6.81,575,483,945","DFWR0007-RD1.0W,,5.28,5.02,7.92,675,568,1105","DFWR0007-RD1.0Y,,5.28,5.02,7.92,675,568,1105","DFWR0007W\/BND,,2.55,2.42,3.83,385,333,593","DFWR0008BD-RD.50W,,4.96,4.71,7.44,825,725,1229","DFWR0008-CSH1.0W,,4.62,4.39,6.93,1075,982,1451","DFWR0008-RD.50W,,4.81,4.57,7.22,1075,978,1467","DFWR0008-RD.75W,,4.81,4.57,7.22,1075,978,1467","DFWR0008-RD1.0W,,4.59,4.36,6.89,1075,982,1449","DFWR0008-TRD7.0W,,5,4.75,7.5,1075,974,1482","DFWR0008W\/BND,,2.23,2.12,3.35,460,415,642","DFWR0012BD-RD.50W,,4.56,4.33,6.84,580,488,951","DFWR0012P-RD.50TTR***,,4.56,4.33,6.84,835,743,1206","DFWR0012-RD.50TTR,,4.31,4.09,6.47,725,638,1076","DFWR0012-RD.50TY,,5.29,5.03,7.94,725,618,1156","DFWR0016W,,2.1,2,3.15,575,533,746","DFWR0028-PRD10x6.5W,,4.05,3.85,6.08,1000,918,"
Now that is not one line
DFRWR2496W/BND*,,2.65 ,2.52 ,3.98 ,910,856,1126,
It seems its taking maybe 1024 characters? How am i suppose to parse it like it shows in excel
fgetcsv is not detecting line endings, add this before call to fopen:
ini_set('auto_detect_line_endings', true);
Processing CSV File in PHP that able to cater MS and UNIX Line Break
Related
How to read a range of rows from CSV file to JSON array using PHP to handle large CSV file?
The target is how to read a range of rows/lines from large CSV file into a JSON array in order to handle large files and read the data in pagination method, each page fetches a range of lines ( e.x. page number 1 fetch from line 1 to 10, page number 2 fetch from line 11 to line 20, and so and ). the below PHP script read from the being CSV file to the desired line ($desired_line), My question is how we can determine the starting line to read from a specific line ($starting_line) <?php // php function to convert csv to json format function csvToJson($fname, $starting_line, $desired_line) { // open csv file if (!($fp = fopen($fname, 'r'))) { die("Can't open file..."); } //read csv headers $key = fgetcsv($fp,"1024","\t"); $line_counter = 0; // parse csv rows into array $json = array(); while (($row = fgetcsv($fp,"1024","\t")) && ($line_counter < $desired_line)) { $json[] = array_combine($key, $row); $line_counter++; } // release file handle fclose($fp); // encode array to json return json_encode($json); } // Define the path to CSV file $csv = 'file.csv'; print_r(csvToJson($csv, 20, 30)); ?>
You should use functions like: fgets() to read the file line by line fseek() to move to the position of the last fgets() of the chunk ftell() to read the position for fseek() Something like this (it's only a schema): <?php ... $line_counter = 0; $last_pos = ... $fseek($fp,$last_pos); while($line = fgets($fp)){ // read a line of the file $line_counter++; (...) // parse line of csv here if($line_counter == 100){ $lastpos = ftell($fp); (...) // save the $lastpos for next reading cycle break; } } ... ?> You can also skip the fseek() and ftell() part and just count the lines every time from the beginning, but that will generally have to go through the whole file from the beginning till the desired lines.
read the first line of the txt file then delete that line with php
I have a huge txt file that have 475254 lines and with php I want to read the first line of the my txt file and save it into the Variable and then when I save it the php delete that line. my txt file is about 2.3 MB is it possible to do this?
yes it is /................................. OK less trolling.. You want fopen and fgets will grab a line. REF : fgets Manual PHP $file = "file.txt" $f = fopen($file, 'r'); $line = fgets($f); fclose($f); // You close because you only want the first one. There are so many examples how to do this i feel embarrassed answering. You should show some of what you have tried first! Now you want to remove it: use file_get_contents REF : PHP file_get_contents //Get your file contents $newDoc = file_get_contents($file, true); $newFileContents = substr( $line, strpos($newDoc, "\n")+1 ); //then you want to save it file_put_contents($newFileContents, $file); I might be wrong but you get the idea!~ ;) Process : Get Contents of file Get First Line Replace content of all file with your First Line as New Line Save File Im sure there is a more efficient way to do this, im just winging! NOTE: You may need to configure your php.ini to work with larger files!
yes, Mark is probably too lazy to even try bulid a code, but i have already a working code so.. copypasta $file = "mydata.txt"; $f = fopen($file, 'r'); $line = fgets($f); fclose($f); //do smth $contents = file($file, FILE_IGNORE_NEW_LINES); $first_line = array_shift($contents); file_put_contents($file, implode("\r\n", $contents)); //sleep(1);
php excel read returning weird characters
I'm using this function to read rows from csv file. <?PHP $file_handle = fopen("test.csv", "r"); while (!feof($file_handle) ) { $line_of_text = fgetcsv($file_handle, 1024); echo $line_of_text[0] . $line_of_text[1]. $line_of_text[2] . "<BR>"; } fclose($file_handle); ?> And I'm getting this PK!|l˜l [Content_Types].xml ¢( Ì”]KÃ0†ïÿCÉ4Ù&ˆÈº]øq©çˆÍé–&!'›Û¿÷4û#¤nzÓÐæœ÷}’4ïp¼jL¶„€ÚÙ‚õye`K§´ìmú”ß²£´Jg¡`k#6]^§k˜Q·Å‚Õ1ú;!°¬¡‘ÈK3•ŒôfÂËr.g ½Þ(`c[ 6>#%&f+ú¼! `e÷›ÂÖ«`Ò{£K‰Túæ’o8u¦¬µÇ+Â`¢Ó¡ùÙ`Û÷B[´‚l"C|– aˆ•.Ìß›óÃ"”®ªt Ê•‹†v€£ Ö±1<¼‘Úî¸ø§bi蟤]_>‘cðO8®ÿˆ#Òÿ"=$IæÈ`\À3¯v#z̹–Ôk”gøª}ˆƒîÑ$8”(Nß…]d´Ý¹'!QÃ>4º.ßÞ‘ÒètÃo·Ú¼S :¼EÊ×Ñ'ÿÿPK!µU0#õL_rels/.rels ¢( Œ’ÏNÃ0ÆïH¼CäûênH¡¥»LH»!TÀ$îµ£$#÷ö„‚JcÛÑöçÏ?[ÞîæiTb/Nú(A±3b{×jxŸV b"giÇŽaWÝÞl_x¤”›b×û¨²‹‹º”ü#b4Oñìr¥‘0QÊahÑ“¨eÜ”å=†¿P-<ÕÁj{ª>ú<ù²·4Mox/æ}b—NŒ#ž;ËvåCf©ÏÛ¨šBËIƒóœÓÉû"cž&Ú\Oôÿ¶8q"K‰ÐHàó<ߊs#ëë.Ÿh©ø½Î<⧄áMdøaÁÅT_ÿÿPK!Þ ý(Ôxl/_rels/workbook.xml.rels ¢( ¼“ÏjÃ0ÆƒÑ}q’ne”:½ŒA¯[÷&QâÐÄ6–ö'o?“Cº#É.¡ƒ$ü}?Чýá§ïÄjU%)´¥«ZÛ(ø8½><ƒ Ö¶Ò³¨`#‚Cq·ÃNsüD¦õ$¢Š%†Ù襤Ò`¯)qmœÔ.ôšcéuyÖ Êõ’ýãšöO /îc)ÇwÚ‡œÝbñÿÿPK!«h&¨bqxl/workbook.xmlŒRËNÃ0¼#ñ–ï4©Ó·šTB€è!QÚ³‰7UÇŽl‡´ÏÆQKQ/œv×;ÏŒ³\+E¾Á:itJ‡ƒ˜Ð¹RïSú¹yy˜Qâ<ׂ+£!¥'pt•Ýß-[c_Æh—ÒÒûzE./¡ân`jи)Œ¸ÇÑî#W[à•¾R‹ãITq©iÏ°°ÿá0E!sx2ySö=‰Å=Êw¥¬Í–…T°í^×o¼BÝGE‰âÎ?éA¤tŒ£iáÏmêÇF*ÜΓ˜Ñ(»˜|·D#Áå7hïÌŽy±c“ÙE±•Ðºßº‘wRÓ¦t4ÃhOç)Á¡ ›¾L)›N稩?{¹/=Ò'É8îØ£+ú ^*ÑÁÝGê_ª«k4€½]HlìZ;†4»BcAß7èä ýuŽ’r®rŒª+AÄhÓ8h{w†ýK’ ÇcÌxLÚÞœHïÚÖûï]Å›*$A°>–›¸í…J%›•ŠôaËËACMÒÛʈ÷¼ÆJꟉ&Mœ;žÖ4BÎe— tˆYÛ>c~4$”‡– I have tried many other but getting the same output. Is there any way I can get string? Thanks in advance.
This is not a CSV file, it is a ZIP file (note the PK at the beginning). Probably this is an xlsx file (excel in xml inside a zip package) that you either misnamed or that has the full name test.csv.xlsx but Windows is hiding your real extension (if you are on Windows).
Try to give lineseperator of your csv file like $csvcontent = fgetcsv($handle, 1000,"\t"); where "\t" is your line seperator.and I think it is not an CSV file...either it is an Zipped file or like .xlsx extended file,First check it once
PHP and CSV file - how to detect end of line? [duplicate]
This question already has answers here: Closed 10 years ago. Possible Duplicate: how to extract data from csv file in php I have some data in XLS, I save them as CSV, the delimiter is **comma*. Then I am trying to load the data from this CSV file: $input = explode("\r\n", fread($file, filesize("my_data.csv"))); print_r($input); The output: Array ( [0] => data from the CSV file) This is the problem - in the array is always just one item, where are printed out all data from the CSV file. How is that possible? Why isn't in the array as much items as is rows in the CSV file? Also, I've tried to change "\r\n" for "\n", but it's the same. What I am trying to do - load each line from the CSV file and this each line to process. EXAMPLE OF THE FILE: a,b,c,d e,f,g,h OUTPUT: a,b,c,d e,f,g,h
I'd recommend using php's built in csv file reading function fgetcsv() and not create your own: http://php.net/manual/en/function.fgetcsv.php if (($handle = fopen($file, "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $row = implode (",",$data); //puts back together the row from the csv echo $row. "\n"; //assuming you want a visual linebreak on console, add the \n } fclose($handle); }
How I solved this issue: In the XLS file, before exporting the file into CSV, I added in the end of sheet one more column with the char '.
How to concatenate two strings using fgetcsv and fputcsv?
I'm creating a script that will read a csv file and display it on a textarea using fgetcsv. $handle = #fopen($filePath, "r"); if ($handle) { while (($buffer = fgetcsv($handle, 1000,",")) !== false) { foreach($buffer as $buff){ echo $buff."\n"; } } } The format of the csv is "line1-content1","line1-content2" "line2-content1","line2-content2" Using fgetcsv, the content will display inside the textarea without double-quote and comma. Can I format it so that it will also display the duoble quotes and comma? Then upon saving it using fputcsv $file_to_load = $_GET['filepath']; $filePath = $dir.$file_to_load; $trans = trim($_POST['txtarea']); $keyarr = split("\n",$trans); $fp = fopen($filePath, 'w'); foreach (array ($keyarr) as $fields) { fputcsv($fp, $fields); } fclose($fp); Looking on the csv file, it saved the csv but displays it like this "line1-content1 ","line1-content2 ","line2-content1 ","line2-content2" It separates the "line1-content1" and "line1-content2" into two lines and put a comma after the end of every line. Now I want to keep the formatting of #2. How will I code it? Can you guide me into the right direction? Thanks!
Sounds like you want to display the actual raw CSV text, not the parsed data within the CSV. Instead of using fgetcsv(), just use fgets() and you'll get the text line without any parsing, preserving the quotes and commas. As for fputcsv, it's going to write out what you pass into it, so make sure that whatever's coming back from the form is cleaned up (e.g. extra line breaks stripped out).