|
użytkowników online: 61
|
OPINIE UŻYTKOWNIKÓW
|
Porady zamieszczone tutaj przez Darka są pomocne w wielu chwilach. Wielokrotnie tworząc jakiś złożony serwis korzystam z tych porad. Można by tworzyć samemu te skrypty, ale tak naprawdę czy nie lepiej jest wziąć skrypt z tej strony i zmodyfikowac go dla swoich potrzeb? Wprawdzie możemy taki skrypt napisać sami, ale po co, skoro stracimy czas na coś, co ktoś juz napisał, przetestował i może zagwarantować, że działa poprawnie. Któryś raz z rzędu opłacam abonament i nie raz jeszcze opłacę. Kawał dobrej roboty i ogrom wiedzy w jednym miejscu.
Piotr Karamański Design Studio
|
|
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net
[Spis]
[A]
[B]
[C]
[D]
[E]
[F]
[G]
[H]
[I]
[J]
[K]
[L]
[M]
[N]
[O]
[P]
[Q]
[R]
[S]
[T]
[U]
[V]
[X]
[W]
[Z]
fgetcsv (PHP 3 >= 3.0.8, PHP 4, PHP 5) fgetcsv -- Pobiera linię ze wskanika pliku i przetwarza na pola CSV Opisarray fgetcsv ( resource uchwyt [, int długość [, string delimiter [, string ogranicznik]]] )
- uchwyt
Ważny uchwyt pliku, poprawnie otwartego za pomocą fopen(),
popen() lub fsockopen().
- długość (opcjonalny)
Musi być większy niż najdłuższa linia (w znakach), która znajduje się w pliku CSV
(wliczając znaki końca lini). Stał się opcjonalny w PHP 5. Opuszczenie
tego parametru (lub ustawienie go na 0 w PHP 5.0.4 lub późniejszym) spowoduje, że
maksymalna długość lini nie jest limitowana, co jest nieznacznie wolniejsze.
- delimiter (opcjonalny)
Ustawia delimeter (tylko jeden znak) pól. Domyślnie przecinek.
- ogranicznik (opcjonalny)
Ustawia znak ograniczający pole. Domyślnie jest to cudzysłów. Dodano w PHP 4.3.0.
Działa podobnie do fgets() tylko, że
fgetcsv() przetwarza odczytaną linię na pola
w formacie CSV i zwraca tablicę zawierającą
odczytane pola.
fgetcsv() zwraca FALSE gdy wystąpi błąd, włączając
w to koniec pliku.
Notatka:
Pusta linia w pliku CSV zostanie zwrócona jako tablica
składająca się z pojedynczego pola null i nie zostanie potraktowana
jako błąd.
Przykład 1.
fgetcsv() przykład - Odczyt i wyświetlenie całej
zawartości pliku CSV
|
<?php
$row = 1;
$uchwyt = fopen ("test.csv","r");
while (($data = fgetcsv($uchwyt, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num pól w lini $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose ($uchwyt);
?>
|
|
fgetcsv() jest bezpieczna binarnie od PHP 4.3.5
Notatka:
Ustawienia lokale są brane pod uwagę przez tę funkcję. Jeśli
LANG jest ustawione na np. en_US.UTF-8,
pliki z jedno bajtowym kodowaniem zostaną nieprawidłowo odczytane
przez funkcję.
Notatka: W przypadku problemów z
rozpoznawaniem znaków końca linii przez PHP przy czytaniu
plików stworzonych lub znajdujących się na komputerach Macintosh, może pomóc
włączenie dyrektywy konfiguracji auto_detect_line_endings.
Patrz także: explode(), file(),
pack() i fputcsv().
User Contributed Notesgibson.a.paul at gmail.com
02-Dec-2005 11:14
a simple script to output the contents of a CSV file as a nice table - should be totally dynamic and can use any seperator - it does not have to be a comma (,).
I don't perclaim my code is 100% perfect or correct, but it works. useful if you back up your cell phone address book and it outputs CSV.
It works on the assumtion that the first line is the header row.
<?
$sep = ",";
$file = "test.txt";
$lines = file($file);
$numlines = count($lines);
$headers = explode($sep, $lines[0]);
$numheaders = count($headers);
$i = 0;
echo "<table border = 1 cellpadding = 2><tr>";
while($i<$numheaders){
$headers = str_replace("\"", "", $headers);
echo "<td>".$headers[$i]."</td>";
$i++;
}
echo "</tr>";
$y = 1;
while($y<$numlines){
$x=0;
echo "<TR>";
while($x<$numheaders){
$fields = explode($sep, $lines[$y]);
$fields = str_replace("\"", "", $fields);
echo "<TD> ".$fields[$x]." </TD>";
$x++;
}
$y++;
echo "</TR>";
}
echo "</table>";
?>
donnoman at donovanbray dot com
23-Nov-2005 04:48
/**
* Based on an example by ramdac at ramdac dot org
* Returns a multi-dimensional array from a CSV file optionally using the
* first row as a header to create the underlying data as associative arrays.
* @param string $file Filepath including filename
* @param bool $head Use first row as header.
* @param string $delim Specify a delimiter other than a comma.
* @param int $len Line length to be passed to fgetcsv
* @return array or false on failure to retrieve any rows.
*/
function importcsv($file,$head=false,$delim=",",$len=1000) {
$return = false;
$handle = fopen($file, "r");
if ($head) {
$header = fgetcsv($handle, $len, $delim);
}
while (($data = fgetcsv($handle, $len, $delim)) !== FALSE) {
if ($head AND isset($header)) {
foreach ($header as $key=>$heading) {
$row[$heading]=(isset($data[$key])) ? $data[$key] : '';
}
$return[]=$row;
} else {
$return[]=$data;
}
}
fclose($handle);
return $return;
}
junk at vhd dot com dot au
14-Nov-2005 01:46
Based on my observations a few comments below I have written a class that incorporates all these features. Here is the class description:
----------
This class will parse a csv file in either standard or MS Excel format.
Two methods are provided to either process a line at a time or return the whole csv file as an array.
It can deal with:
- Line breaks within quoted fields
- Character seperator (usually a comma or semicolon) in quoted fields
- Can leave or remove leading and trailing spaces or tabs
- Can leave or skip empty rows.
- Windows and Unix line breaks dealt with automatically. (Care must be taken with Macintosh format.)
Also, the escape character is automatically removed.
-----------
So basically it should "just work". If it doesn't please send me an email ;-)
You can download it from: http://www.phpclasses.org/browse/package/2672.html
An example on how to use the class and a test.csv file are also provided.
tokai at binaryriot dot com
07-Nov-2005 11:18
Newer PHP versions handle cvs files slightly different than older versions.
"Max Mustermann"|"Muster Road 34b"|"Berlin" |"Germany"
"Sophie Master" |"Riverstreet" |"Washington"|"USA"
The extra spaces behind a few fields in the example (which are useful, when you manually manage a small csv database to align the columns) were ignored by fgetcsv from PHP 4.3. With the new 4.4.1 release they get appended to the string, so you end up with "Riverstreet " instead the expected "Riverstreet".
Easy workaround is to just trim all fields after reading them in.
while ( $data = fgetcsv($database, 32768, "|") )
{
$i = 0;
while(isset($data[$i]))
{
$data[$i] = rtrim($data[$i]);
$i++;
}
....
}
junk at vhd dot com dot au
25-Oct-2005 06:52
The fgetcsv function seems to follow the MS excel conventions, which means:
- The quoting character is escaped by itself and not the back slash.
(i.e.Let's use the double quote (") as the quoting character:
Two double quotes "" will give a single " once parsed, if they are inside a quoted field (otherwise neither of them will be removed).
\" will give \" whether it is in a quoted field or not (same for \\) , and
if a single double quote is inside a quoted field it will be removed. If it is not inside a quoted field it will stay).
- leading and trailing spaces (\s or \t) are never removed, regardless of whether they are in quoted fields or not.
- Line breaks within fields are dealt with correctly if they are in quoted fields. (So previous comments stating the opposite are wrong, unless they are using a different PHP version.... I am using 4.4.0.)
So fgetcsv if actually very complete and can deal with every possible situation. (It does need help for macintosh line breaks though, as mentioned in the help files.)
I wish I knew all this from the start. From my own benchmarks fgetcsv strikes a very good compromise between memory consumption and speed.
-------------------------
Note: If back slashes are used to escape quotes they can easily be removed afterwards. Same for leading and trailing spaces.
mortanon at gmail dot com
14-Oct-2005 05:05
Hier is an example for a CSV Iterator.
<?php
class CsvIterator implements Iterator
{
const ROW_SIZE = 4096;
private $filePointer = null;
private $currentElement = null;
private $rowCounter = null;
private $delimiter = null;
public function __construct($file, $delimiter=',')
{
try {
$this->filePointer = fopen($file, 'r');
$this->delimiter = $delimiter;
}
catch (Exception $e) {
throw new Exception('The file "'.$file.'" cannot be read.');
}
}
public function rewind() {
$this->rowCounter = 0;
rewind($this->filePointer);
}
public function current() {
$this->currentElement = fgetcsv($this->filePointer, self::ROW_SIZE, $this->delimiter);
$this->rowCounter++;
return $this->currentElement;
}
public function key() {
return $this->rowCounter;
}
public function next() {
return !feof($this->filePointer);
}
public function valid() {
if (!$this->next()) {
fclose($this->filePointer);
return false;
}
return true;
}
}
?>
Usage :
<?php
$csvIterator = new CsvIterator('/path/to/csvfile.csv');
foreach ($csvIterator as $row => $data) {
}
?>
Vladimir Gruzdev
20-Sep-2005 05:09
"cristian DOT zuddas AT gmail DOT com" has posted the corrected function "CSV2Array", but all the same there's an error. For example, function incorrectly processes a simple csv-file from "MS Excel" (http://wsCat.ka.pp.ru/test.csv) in which fields any way contain quotes and CR/LF . I has written working function which has successfully applied to import of the greater production catalog.
<?php
$str=file_get_contents('http://wsCat.ka.pp.ru/test.csv');
$rows=CSV2Array($str);
echo '<table border="1" cellSpacing="2" cellPadding="2">';
for($i=0;$i<count($rows);$i++)
{
echo '<tr>';
for ($j=0;$j<count($rows[$i]);$j++)
{
echo '<td>'.$rows[$i][$j]. '</td>';
}
echo '</tr>';
}
echo '</table>';
function CSV2Array($content)
{
if ($content{strlen($content)-1}!="\r" && $content{strlen($content)-1}!="\n")
$content .= "\r\n";
$arr=array();
$temp=$content;
$tma=array();
while (strlen($temp)>0)
{
if ($temp{0}=='"')
{
$temp=substr($temp,1);
$str='';
while (1)
{
$matches=array();
if (!preg_match('/^(.*?)"("*?)(;|\r\n)(.*)$/is',$temp,$matches))
return $arr;
$temp=$matches[4];
if (fmod(strlen($matches[2]),2)>0)
{
$str.=$matches[1].$matches[2].'"'.$matches[3];
continue;
}
else
{
$tma[]=preg_replace('/""/','"',$str.$matches[1].$matches[2]);
if ($matches[3]!=';')
{
$arr[]=$tma;
$tma=array();
}
break;
}
}
}
else
{
$matches=array();
if (!preg_match('/^([^;\r\n]*)(;|\r\n)(.*)$/is',$temp,$matches))
return $arr;
$tma[]=$matches[1];
$temp=$matches[3];
if ($matches[2]!=';')
{
$arr[]=$tma;
$tma=array();
}
}
}
return $arr;
}
?>
at lapstore doot de the webmaster
26-Aug-2005 04:16
Some of you might need this:
CSV-Parser optimized for -speed- which can handle linebreaks in quoted strings
This parser can not handle unquoted data containing quotes ("), i.e. apple, ban"ana, cherry
<?php
$csv_data = "apple; banana; \"multi-\nline\";\"string with \"\" quoted quotes\";\n";
$csv_data .= "second;line;with;trailing;colon\n";
$csv_data .= "third;line;without;trailing;colon;";
$prepared = csv_prepare($csv_data);
while ($myrow = csv_getrow(&$prepared, false)) {
echo "Row ".csv_rownumber(&$prepared).": ";
for ($i = 0;$i < $myrow["c"]; $i++) echo "[".htmlspecialchars($myrow[$i])."]";
echo "<BR>\n";
}
function csv_prepare($data) {
$rc = array();
$rc[0] = strtr($data,array("\r\n" => "\n"));
$rc[0] = strtr($rc[0],array("\r" => "\n"));
$rc[1] = 0;
$rc[2] = strlen($rc[0]);
$rc[3] = 0;
return $rc;
}
function csv_rownumber(&$data) {
return $data[3];
}
function csv_getrow(&$data, $chopnl) {
$data[3] += 1;
$rc = array();
$line = csv__getline(&$data);
$line = trim($line);
$len = strlen($line);
$start = 0;
if ($len == 0 && $data[1] >= $data[2]) {
return false;
}
$iter = 0;
while ($iter < 500) {
$item = csv__getitem(&$line, $chopnl, &$start, $len);
$rc[$iter] = $item;
$iter += 1;
if ($start >= $len) break;
}
$rc["c"] = $iter;
return $rc;
}
function csv__getline(&$data) {
$sep = csv__extract(&$data[0], "\n", $data[1], $data[2]);
$oi = $data[1];
$data[1] = $sep + 1;
return substr($data[0],$oi,$sep - $oi);
}
function csv__getitem(&$data, $chopnl, &$start, $len) {
$sep = csv__extract(&$data, ";",$start, $len);
$rc = trim(substr($data,$start,$sep - $start));
$start = $sep + 1;
if (substr($rc,0,1) == "\"") {
if (substr($rc,strlen($rc) - 1,1) == "\"") {
$rc = substr($rc,1,strlen($rc) - 2);
}
}
$rc = strtr($rc,array("\"\"" => "\""));
if ($chopnl) {
$rc = strtr($rc,array("\n" => " "));
}
return trim($rc);
}
function csv__extract(&$data, $sep, $startidx, $len) {
$instr = false;
for ($i=$startidx;$i < $len; $i+=1) {
$c = $data[$i];
if ($c == "\"") {
if ($instr) {
$c2 = ($i < $len - 1) ? $data[$i + 1] : "";
if ($c2 == "\"") {
$i += 1;
continue;
} else {
$instr = false;
}
} else {
$instr = true;
}
} elseif ($c == $sep) {
if ($instr) {
continue;
} else {
return $i;
}
}
}
return $len;
}
?>
andychr17 at hotmail dot com
05-Aug-2005 09:30
The man below suggested this to avoid and endless loop from using "!== FALSE":
while (($data = fgetcsv($handle, 1000, ",")) != FALSE) {
This is redundant, if you want to do it with the != you may as well do:
while ($data = fgetcsv($handle, 1000, ",")) {
essaym.net
29-Jun-2005 09:17
Heres a function i wrote because all the other functions on here didnt work quiet as easy as I wanted them to:
It opens the CSV file, and reads it into a 3d array. If you set $columnsOnly, you will only get the first line.
<?php
function CSV2Array($openFile, $columnsOnly = false)
{
$handle = fopen ($openFile,"r");
$rows = 0;
while (!feof($handle)) {
$columns[] = explode(",", fgets($handle, 4096));
if ($rows++ == 0 && $columnsOnly)
break;
}
fclose ($handle);
return $columns;
}
?>
cristian DOT zuddas AT gmail DOT com
17-Jun-2005 03:58
"marc at henklein dot com" posted a cool function "CSV2Array", but there's an error. If the last char of the CSV file isn't a carriage return, the function can't take the last field of the last line in the CSV.
Fixed adding this check:
<?
if ($content[strlen($content)-1]!="\r" && $content[strlen($content)-1]!="\n")
$content .= "\r\n";
?>
The updated function:
<?
function CSV2Array($content, $delim = ';', $encl = '"', $optional = 1) {
if ($content[strlen($content)-1]!="\r" && $content[strlen($content)-1]!="\n")
$content .= "\r\n";
$reg = '/(('.$encl.')'.($optional?'?(?(2)':'(').
'[^'.$encl.']*'.$encl.'|[^'.$delim.'\r\n]*))('.$delim.
'|\r\n)/smi';
preg_match_all($reg, $content, $treffer);
$linecount = 0;
for ($i = 0; $i<=count($treffer[3]);$i++) {
$liste[$linecount][] = $treffer[1][$i];
if ($treffer[3][$i] != $delim)
$linecount++;
}
unset($linecount);
unset($i);
unset($reg);
unset($content);
unset($delim);
unset($encl);
unset($optional);
unset($treffer);
return $liste;
}
?>
Bart
17-Jun-2005 01:08
The file function reads the file in an array with the EOL still attached, so the +1 is not necessary.
Bob Kolk
17-May-2005 06:50
Dave Meiners above example is great, except that you need to need to add one to the final length to account for EOL. So it'd be:
while ($data = fgetcsv($handle, ($length+1), ","))
marc at henklein dot com
21-Feb-2005 01:57
for excel-csv-sheets like:
test1;test2;test3;test4;"test5
test5b
test5c";test6
(optionally enclosed by " including line-breaks)
.. i wrote a little function to solve this problem.
<?php
function CSV2Array($content, $delim = ';', $encl = '"', $optional = 1)
{
$reg = '/(('.$encl.')'.($optional?'?(?(2)':'(').
'[^'.$encl.']*'.$encl.'|[^'.
$delim.'\r\n]*))('.$delim.'|\r\n)/smi';
preg_match_all($reg, $content, $treffer);
$linecount = 0;
for ($i = 0; $i<=count($treffer[3]);$i++)
{
$liste[$linecount][] = $treffer[1][$i];
if ($treffer[3][$i] != $delim)
$linecount++;
}
return $liste;
}
$content = join('',file('test.csv'));
$liste = CSV2Array($content);
print_r($liste);
?>
slyi
19-Feb-2005 07:05
heres a version that take a bugzilla url and spits the results as rss
<?php
$bugzillaurl="http://www.reactos.com/bugzilla/";
$bugquery= $bugzillaurl . "buglist.cgi?query_format=&bug_severity=blocker&ctype=csv";
header('Content-type: text/xml');
echo "<?xml version=\"1.0\" ?>\n";
?>
<rss version="2.0">
<channel>
<title>bugzilla csv2rss</title>
<link><?=$bugzillaurl?></link>
<description>bugzilla csv2rss</description>
<language>en-us</language>
<?php
$row = 0;
$handle = fopen($bugquery, "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($row == '0') { $row = '8';} else{ $row++;
echo "<item>\n";
echo "<title>" . htmlspecialchars($data[7], ENT_QUOTES) . "</title>\n";
echo "<description>" . htmlspecialchars($data[7], ENT_QUOTES) . "</description>\n";
echo "<link>" . $bugzillaurl . "show_bug.cgi?id=" . $data[0] . "</link>\n";
echo "</item>\n";
}
}
fclose($handle);
?>
</channel>
</rss>
ramdac at ramdac dot org
24-Jan-2005 06:40
Be wary of Example #1 above.
If the file doesn't exist, the application will spit out data to STDOUT and could fill up /tmp space if you're not careful. The output might will look like this:
PHP Warning: fgetcsv(): supplied argument is not a valid stream resource in...(your filename here)
To get around this, do the following:
<?
row = 1;
if(!$handle = fopen("test.csv", "r"))
{
print 'could not open file. quitting';
die;
}
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);
?>
Daffy
22-Nov-2004 03:25
This is a little sniplet for all users who has problems with Excel csv files. This functions does almost the same like the linux shell program dos2unix.
/* ------------------8<------------------------*/
function dos2unix ($filename) {
//open original file
$fp = fopen($filename,'r');
//open original file
$fptmp = fopen($filename.'_tmp','w');
while(!feof($fp)){
$line = chop(fgets($fp,4096));
$ret = ereg_replace(chr(13) . chr(10),"\n",$line);
$ret = ereg_replace(chr(13),"\n",$ret);
fwrite($fptmp,$ret);
}
fclose($fp);
fclose($fptmp);
//remove original file
unlink($filename);
//move converted file to old filename
copy($filename.'_tmp', $filename);
//remove temp file
unlink($filename.'_tmp');
}
/* ------------------8<------------------------*/
18-Nov-2004 07:47
example 1 above goes into an infinte loop if the file name is bad because fgetcsv return a false result not identical to false but equl to false
to fix this use != instead of !== in the test as shown below it will still work correctly for the case when the file exists.
while (($data = fgetcsv($handle, 1000, ",")) != FALSE) {
mickoz[at]parodius[dot]com
31-Oct-2004 12:54
In "php at dogpoop dot cjb dot net" post, I would change in his function:
function csv_split($line,$delim=',',$removeQuotes=true)
this code:
if ($line[$i+1] == '"') {
to:
if ($i+1 < strlen($line) && $line[$i+1] == '"') {
The reason is that if the quote (") is at the last line of the string, then it will try to reach an undefined space in the string, therefore giving a PHP error.
Of course his function is great if your line is a true compatible csv line, but I leave that to you to judge if you can do this assumption ;-)
aidan at php dot net
01-Jul-2004 03:47
dave146 at burtonsys dot com
18-Jun-2004 10:29
To convert .dbf files (dBase/xBase/FoxPro/Clipper/etc.) files
to .csv, so that you can read them with fgetcsv, get dbf2csv.zip
from http://www.burtonsys.com/downloads.html
(It seems odd to me that php has fgetcsv but no splitcsv.)
-Dave
jc at goetc dot net
17-Jun-2004 05:51
I've had alot of projects recently dealing with csv files, so I created the following class to read a csv file and return an array of arrays with the column names as keys. The only requirement is that the 1st row contain the column headings.
I only wrote it today, so I'll probably expand on it in the near future.
<?php
class CSVparse
{
var $mappings = array();
function parse_file($filename)
{
$id = fopen($filename, "r"); $data = fgetcsv($id, filesize($filename)); if(!$this->mappings)
$this->mappings = $data;
while($data = fgetcsv($id, filesize($filename)))
{
if($data[0])
{
foreach($data as $key => $value)
$converted_data[$this->mappings[$key]] = addslashes($value);
$table[] = $converted_data; } } fclose($id); return $table;
}
}
?>
dawa at did-it dot com
12-Apr-2004 09:30
The following modification will hide the unnecessary delimiter in the array
that is returned when fgetcsvfromline is called.
<?php
function fgetcsvfromline ($line, $columnCount, $delimiterChar = ',',
$enclosureChar = '"') {
global $regExpSpecialChars;
$matches = array();
$delimiterChar = strtr($delimiterChar, $regExpSpecialChars);
$enclosureChar = strtr($enclosureChar, $regExpSpecialChars);
$cutpoint = strlen($delimiterChar)+1;
$regExp = "/^";
for ($i = 0; $i < $columnCount; $i++) {
$regExp .= $enclosureChar.'?(.*?)'.$enclosureChar.'?'.$delimiterChar;
}
$regExp = substr($regExp,0,-$cutpoint).'/';
if (preg_match($regExp, $line, $matches)) {
return $matches;
}
return 0;
}
?>
=== If you were getting
[0] => "Ma"rk","Bergeron","rocks","12345,"times"
[1] => "
[2] => Ma"rk
[3] => "
..etc
You will now get
[0] => "Ma"rk","Bergeron","rocks","12345,"times"
[1] => Ma"rk
...etc
bu at orbitel dot bg
18-Mar-2004 05:54
I found a way to parse CSVs with Perl RegExps and it's a lot faster and more efficient than the conventional fgetcsv() way.
The fgetcsv() took more than 2 minutes to parse a 15,000 lined file while my function takes 6 to 7 secs on a Celeron 366 MHz prehistoric machine.
Here's a link to the source of my function.
fgetcsvfromline() source
http://bu.orbitel.bg/fgetcsvfromline.php
fgetcsvfromline() in action
http://bu.orbitel.bg/csv.php
Please let me know if you use it or if you've found a better solution.
Dave Meiners
05-Feb-2004 05:37
using the example above with a length of 1000 will truncate any csv rows longer than 1000 bytes, the remainder of that line will be represented next time you call $data = fgetcsv(). one solution i have seen to this is to use filesize("test.csv") as the length argument, however sometimes with large csv files you may encounter errors for exceeding the memory limit. to remedy this, i have read the csv file into an array, looping through that array to find the longest line in the csv, and then using that value as my length argument, unset($array) to free up the memory. im open to better solutions.
<?php
$length = 1000;
$array = file("test.csv");
for($i=0;$i<count($array);$i++)
{
if ($length < strlen($array[$i]))
{
$length = strlen($array[$i]);
}
}
unset($array);
$handle = fopen("test.csv", "r");
while ($data = fgetcsv($handle, $length, ","))
{
}
fclose($handle);
?>
guntars at datapro dot lv
27-Nov-2003 02:24
For all those people struggling with Macintosh conversions, since PHP 4.3 there is a new runtime setting available:
auto_detect_line_endings boolean
When turned on, PHP will examine the data read by fgets() and file() to see if it is using Unix, MS-Dos or Macintosh line-ending conventions.
This enables PHP to interoperate with Macintosh systems, but defaults to Off, as there is a very small performance penalty when detecting the EOL conventions for the first line, and also because people using carriage-returns as item separators under Unix systems would experience non-backwards-compatible behaviour.
mjwilco at yahoo dot com
02-Oct-2003 05:35
Here's one way to convert the data in a csv file to an html table:
<?php
$filename = "book1.csv"; $id = fopen($filename, "r"); while ($data = fgetcsv($id, filesize($filename))) $table[] = $data; fclose($id); echo "<table>\n";
foreach($table as $row)
{
echo "<tr>";
foreach($row as $data)
echo "<td>$data</td>";
echo "</tr>\n";
}
echo "</table>\n";
?>
You may need to change the parameters for fgetcsv() to suit your needs and probably change the table style.
elainy at gmx dot net
01-Oct-2003 02:54
I wrote this little thingy to allow the customer to upload csv-files to his page which will then automatically be converted to a php-include-file with a html-table for inclusion in his homepage.
Its a little buggy since it can't handle rowspan and such, but otherwise it works well.
<?php
function csv2php($filename, $delim=';',$path)
{
$row = 0;
$dump = array();
$once = 0;
$max_cols = 0;
$f = fopen ($filename,"r");
$size = filesize($filename)+1;
while ($data = fgetcsv($f,$size,$delim,''))
{
for($o=0;$o<sizeof($data);$o++)
{
if($once==0)
$max_cols++;
}
$dump[$row] = $data;
if($once==0)
$once=1;
$row++;
}
fclose ($f);
$printtext="<table border='0' cellspacing='0' cellpadding='0'>\n";
for($x=0;$x<sizeof($dump);$x++)
{
$printtext.="<tr>\n";
for($y=0,$limiter=0;(($y<sizeof($dump[$x])) || ($limiter<$max_cols));$y++,$limiter++)
{
$printtext.="\t<td>";
if($dump[$x][$y]!='')
$printtext.=$dump[$x][$y];
else
$printtext.=" ";
$printtext.="</td>\n";
}
$printtext.="</tr>\n";
}
$printtext.="</table>\n";
$ident = write_dammit($printtext,$path);
return $ident;
}
function write_dammit($printtext,$path)
{
$ident=time();
$filename=$ident;
$filename .= ".inc.php";
$filecontents = $printtext;
$fp = fopen("$path/$filename","w"); fwrite($fp,$filecontents);
fclose($fp);
return $ident;
}
$ident = csv2php("table.csv",";","C:/your_include_folder/");
require($ident.".inc.php");
?>
chery79 at hushmail dot com
20-Sep-2003 11:18
inserting IP-to-Country Database into mysql
<?
$link = mysql_connect("localhost", "username", "password") or die("Could not connect: ".mysql_error());
$db = mysql_select_db("ip2country") or die(mysql_error());
$row = 1;
$handle = fopen ("ip-to-country.csv","r");
while ($data = fgetcsv ($handle, 1000, ",")) {
$query = "INSERT INTO ip2country(`id`, `ipFrom`, `ipTo`, `country2`, `country3`, `country`) VALUES('".
$row."', '".$data[0]."', '".$data[1]."', '".$data[2]."', '".$data[3]."', '".$data[4]."')";
$result = mysql_query($query) or die("Invalid query: " . mysql_error().__LINE__.__FILE__);
$row++;
}
fclose ($handle);
?>
phpnet at smallfryhosting dot co dot uk
19-Sep-2003 06:42
Another version [modified michael from mediaconcepts]
<?php
function arrayFromCSV($file, $hasFieldNames = false, $delimiter = ',', $enclosure='') {
$result = Array();
$size = filesize($file) +1;
$file = fopen($file, 'r');
if ($hasFieldNames) $keys = fgetcsv($file, $size, $delimiter, $enclosure);
while ($row = fgetcsv($file, $size, $delimiter, $enclosure)) {
$n = count($row); $res=array();
for($i = 0; $i < $n; $i++) {
$idx = ($hasFieldNames) ? $keys[$i] : $i;
$res[$idx] = $row[i];
}
$result[] = $res;
}
fclose($file);
return $result;
}
?>
NOSPAM-michael at mediaconcepts dot nl
15-Sep-2003 04:45
A little contribution to make it more easy to use this function when working with a database. I noticed this function doesn't add logical keys to the array, so I made a small function which creates a 2dimensional array with the corresponding keys added to the rows.
<?php
function convertCSVtoAssocMArray($file, $delimiter)
{
$result = Array();
$size = filesize($file) +1;
$file = fopen($file, 'r');
$keys = fgetcsv($file, $size, $delimiter);
while ($row = fgetcsv($file, $size, $delimiter))
{
for($i = 0; $i < count($row); $i++)
{
if(array_key_exists($i, $keys))
{
$row[$keys[$i]] = $row[$i];
}
}
$result[] = $row;
}
fclose($file);
return $result;
}
?>
ng4rrjanbiah at rediffmail dot com
08-Sep-2003 12:02
Important note about the CSV format:
There should *not* be any space in between the fields. For example,
field1, field2, field3 [Wrong!]
field1,field2,field3 [Correct-No space between fields]
If you add space between the fields, MS Excel won't recognize the fields (especially date and multi-line text fields).
HTH,
R. Rajesh Jeba Anbiah
shaun at linuxhost dot cc
15-Aug-2003 09:03
I've seen alot of people talking about ways to convert from mac to unix or from dos to unix.
For DOS to UNIX I use dos2unix in the "tofrodos Ver 1.4" package.
http://www.thefreecountry.com/tofrodos/index.shtml
For Mac to UNIX I have the follwing in my .bashrc
alias mac2unix="perl -pi -e 'tr/\015/\012/'"
Just run dos2unix or mac2unix <filename> and it will convert. My life has been easier ever since I started installing these utilities.
reptileX at example dot com
12-Aug-2003 09:57
beware of using this function in two different php versions,
in php 4.3 the 4th parameter can be given altough empty
in php 4.2 you get just a warning but it is not able to read the csv file if you place an enclosure that is empty
brian at brianvoss dot com
26-Jul-2003 12:55
If anyone else is taking on the task of converting from FileMaker Pro to MySQL, you might find this useful:
Here's a collection of simple functions that take a CSV file, re-formats the data and writes to a file with MySQL INSERTs.
ORIGINAL DATA:
"1", "foo", "2"
"3", "bar", "4"
OUTPUT
INSERT info mysql_table VALUES('', '1', 'foo', '2');
INSERT info mysql_table VALUES('', '3', 'bar', '4');
For simple data it works alright, but I could not find a way to escape the contents before assembling the INSERT statements - kept getting "bad argument for implode()"...
<?php
$file = "path/to/your/file.txt";
$tbl = "your_MySQL_table";
$CSVarray = get_csv($file);
$CSVarray = makeINSERTS($CSVarray, "$tbl");
$filetowrite = $_POST["file"]."_sql.txt";
$fp = fopen($filetowrite, "w");
while (list($key, $val) = @each($CSVarray)) {
fwrite($fp, $val);
}
fclose($fp);
chmod($filetowrite, 0777);
echo "File written Successfully";
}
function get_csv($filename, $delim =","){
$row = 0;
$dump = array();
$f = fopen ($filename,"r");
$size = filesize($filename)+1;
while ($data = fgetcsv($f, $size, $delim)) {
$dump[$row] = $data;
$row++;
}
fclose ($f);
return $dump;
}
function makeINSERT($text, $table){
$insert = array();
$i = 0;
while (list($key, $val) = @each($text)){
$insert[$i] = "INSERT into ".$table." VALUES('','";
$insert[$i] .= implode("','", $val);
$insert[$i] .= "');\n";
$i++;
}
return $insert;
}
?>
kurtnorgaz at web dot de
21-Jul-2003 09:00
You should pay attention to the fact that "fgetcsv" does remove leading TAB-chars "chr(9)" while reading the file.
This means if you have a chr(9) as the first char in the file and you use fgetcsv this char is automaticaly deleted.
Example:
file content:
chr(9)first#second#third#fourth
source:
$line = fgetcsv($handle,500,"#");
The array $line looks like:
$line[0] = first
$line[1] = second
$line[2] = third
$line[3] = fourth
and not
$line[0] = chr(9)first
$line[1] = second
$line[2] = third
$line[3] = fourth
All chr(9) after another char is not deleted!
Example:
file content:
Achr(9)first#second#third#fourth
source:
$line = fgetcsv($handle,500,"#");
The array $line looks like:
$line[0] = Achr(9)first
$line[1] = second
$line[2] = third
$line[3] = fourth
php at joestump dot net
14-Jul-2003 04:58
For those of you having problems with Excel's version of CSV file exports (which include the infamous ^M characters in *NIX editors, such as VIM) here is a simple script to remove them and replace them in the normal UNIX newline character (\n).
<?
$fp = fopen('/dev/stdin','r');
while(!feof($fp)){
$line = chop(fgets($fp,4096));
$ret = ereg_replace(chr(13) . chr(10),"\n",$line);
$ret = ereg_replace(chr(13),"\n",$ret);
echo $ret."\n";
}
fclose($fp);
?>
Usage: cat file_with_windows_newlines | php -q strip_newlines.php > outfile
(this works for other stuff too, like PHP "coders" who use Notepad and upload to a UNIX environment).
kyle at kghspam at yahoo.com
18-Jun-2003 01:05
Quick and dirty script to take a csv file and turn it into a multidimensional associative array structure using the first line of the csv as the hash key names.
<?
$i = 0;
$handle = fopen ("file.csv","r");
while($data = fgetcsv ($handle, 1000, ",")) {
if ($i == 0) { $key_arr = $data; }
reset($key_arr);
while(list($index,$name) = each($key_arr)) { $temp_arr[$name] = $data[$index]; }
$result_arr[$i] = $temp_arr;
$i++;
}
fclose ($handle);
?>
drudge at php-coders dot net
09-Jun-2003 01:14
Here is a function to read a whole csv file into an array:
<?php
function get_csv($filename, $delim=',')
{
$row = 0;
$dump = array();
$f = fopen ($filename,"r");
$size = filesize($filename)+1;
while ($data = fgetcsv($f, $size, $delim)) {
$dump[$row] = $data;
$row++;
}
fclose ($f);
return $dump;
}
?>
kmlinac/nospam/ at oliver dot /nospam/efos dot hr
09-May-2003 11:12
This is the solution to Microsoft Excel csv file - this function add last delimiter in line.
<?php
function delimiter()
{
if (is_file("file.csv"))
{
$fp = fopen($file.csv,"r");
while (false!=($line = fgets($fp)))
{
$line = "$line;";
putf($line);
}
fclose($fp);
}
}
function putf($line)
{
$fp = fopen($file,"a");
fputs($fp,$line);
fclose($fp);
}
delimiter();
?>
mendi dot susanto at dmetrading dot com
21-Mar-2003 10:07
I've tried the code above but doesn't work, so I tried to modify it... this is the code to get the first line of csv fle, puti it into TABLE 1, while the rest line of csv file will be put at TABLE 2
<?php
$openfile = "tes2.csv";
$row = 0;
$handle = fopen ($openfile,"r");
while ($data = fgetcsv ($handle, 1000, ","))
{
if($row == '0')
{
$num = count ($data);
print "<p> $num fields in line $row: <br>\n";
echo "This belong to TABLE 1 <br>";
for ($c=0; $c < $num; $c++)
{
print $data[$c] . "<br>\n";
}
$row = '32';
}
else
{
$num = count ($data);
print "<p> $num fields in line $row: <br>\n";
$row++;
echo "This belong to TABLE 2 <br>";
for ($c=0; $c < $num; $c++)
{
print $data[$c] . "<br>\n";
}
}
}
fclose ($handle);
?>
17-Feb-2003 08:23
Here's piece of code I wrote that reads the first line of a CSV file, creates an array based the field's name, and then reads the rest of the contents of the CSV file into the approate arrays. Great for quick and dirty access to a CSV file.
<?php
$openFile = "test.csv";
$row = 0;
$handle = fopen ($openFile,"r");
while ($data = fgetcsv ($handle, 1000, ",")) {
if($row == 0){
$num = count ($data);
$csvNames = array();
for ($c=0; $c < $num; $c++) {
$csvNames[$c] = $data[$c];
eval("$" . $data[$c] . " = array();");
}
$row = 1;
}else{
$num = count ($data);
$row++;
for ($c=0; $c < $num; $c++) {
$buildEval = "$" . $csvNames[$c] . "[" . ($row - 1) . "] = \"" . $data[$c] . "\";";
eval($buildEval );
}
}
}
fclose ($handle);
?>
anthony dot thomas at nospam dot com
06-Dec-2002 06:29
fgetcsv stops reading your file?
I had to write a script to validate and import a large amount of data to MySQL and it would stop running. I've noticed, after trawling the internet for a solution, quite a few people have had similar problems.
Solution? Like a dope I had forgotten to put in
set_time_limit()
within a loop. Otherwise the script would time out before it finished importing all the data.
Moral of the story? Only suppress errors after your script works with a large amount of test data!
php at dogpoop dot cjb dot net
16-Nov-2002 05:01
This function takes a csv line and splits it into an array, much like fgetcsv does but you can use it on data that isn't coming in from a file, or you can read data from a file some other way (like if your Mac files aren't being read correctly) and use this to split it. If you have any corrections, comments (good or bad), etc. I would appreciate an email to the above address.
<?php
function csv_split($line,$delim=',',$removeQuotes=true) {
$fields = array();
$fldCount = 0;
$inQuotes = false;
for ($i = 0; $i < strlen($line); $i++) {
if (!isset($fields[$fldCount])) $fields[$fldCount] = "";
$tmp = substr($line,$i,strlen($delim));
if ($tmp === $delim && !$inQuotes) {
$fldCount++;
$i += strlen($delim)-1;
} else if ($fields[$fldCount] == "" && $line[$i] == '"' && !$inQuotes) {
if (!$removeQuotes) $fields[$fldCount] .= $line[$i];
$inQuotes = true;
} else if ($line[$i] == '"') {
if ($line[$i+1] == '"') {
$i++;
$fields[$fldCount] .= $line[$i];
} else {
if (!$removeQuotes) $fields[$fldCount] .= $line[$i];
$inQuotes = false;
}
} else {
$fields[$fldCount] .= $line[$i];
}
}
return $fields;
}
?>
martin dot goldinger at netserver dot ch
28-Oct-2002 03:12
With MAC, use: Save As - CSV for Windows. Then fgetcsv works as expected.
justin at indent dot com dot au
08-Aug-2002 09:24
If you're working in Excel on a Mac and are exporting a spreadsheet as a CSV, PHP won't recognise the line breaks, and interprets the file as one really long line. It borders on a bug really. For me, I just open the file in BBEdit or BBEdit Lite, convert the file from Mac to Unix, and all is well. But if you're dealing with user-contributed files, you'll need to convert the line-endings first... replacing all \r's with \n's should do it.
c dot greenNOSP at Mits dot uq dot edu dot au
24-Jun-2002 05:21
Quoting csv is pretty simple, and there are two steps..I note in previous comments only the second step has been explained.
First fields with double quotes need to double up the quotes, ie _He said "Timmy"..._ should become _He said ""Timmy""..._
Secondly as mentioned above, fields with commas need double quotes.
Here is a simple function to achieve this, that I pass to array walk, if you want to use it somewhere else, prob get rid of reference and return the value.
function check_csv_field_ref(&$item) {
$item = str_replace('"', '""', $item);
if (strpos($item, ",") !== FALSE) {
$item = '"' . $item . '"';
}
}
joeldegan-AT-yahoo.com
12-Jun-2002 10:01
function to parse multi arrays into csv data
array in... array of array(datasets); first dataset = field names.
usage:
$toparse[0][0] = "field1";
$toparse[0][1] = "field2";
$toparse[1][0] = "value1";
$toparse[1][1] = "123123123"; // to see
echo export_to_csv($toparse);
<?php
function export_to_csv($inarray){
while (list ($key1, $val1) = each ($inarray)) {
while (list ($key, $val) = each ($val1)) {
if (is_numeric($val)){
$sendback .= $val.",";
}else{
$sendback .= "\"". $val ."\",";
}}$sendback = substr($sendback, 0, -1); $sendback .= "\n";
}return ($sendback);
}?>
send the file to the client.. pretty simple.
usage: send_file_to_client("data.csv",export_to_csv($data));
<?php
function send_file_to_client($filename, $data){
header("Content-type: application/ofx");
header("Content-Disposition: attachment; filename=$filename");
echo $data;
};
?>
blair at squiz . net
15-Aug-2001 04:19
Here is a function that takes an array and adds a CSV line to the passed file pointer.
<?php
function fputcsv ($fp, $array, $deliminator=",") {
$line = "";
foreach($array as $val) {
$val = str_replace("\r\n", "\n", $val);
if(ereg("[$deliminator\"\n\r]", $val)) {
$val = '"'.str_replace('"', '""', $val).'"';
}$line .= $val.$deliminator;
}$line = substr($line, 0, (strlen($deliminator) * -1));
$line .= "\n";
return fputs($fp, $line);
}?>
|