Reply to comment

CSV Parser for PHP

21 Jan 2008

This is a snippet of code that I had posted on another of my websites and in doing some cleanup it really fits better here.

I spent last evening working on a Comma Separated Values (CSV) list of titles for a project I'm working on. Below is a snippet of code I worked with. The first method from the PHP Cookbook suggests using fgetcsv(). That woks pretty well but the native function in PHP doesn't handle values (fields) that contain separators (commas) very well and doesn't have the concept of multiple values being delimited by a different delimiter within a field. So I whipped up the parser that comes second in the example below.

<?php

$fp

= fopen('filename','r') or die("can't open file");
print
"<table border=\"1\">\n";
while(
$csv_line = fgetcsv($fp,1024, ",", "\"")) {
    print
'<tr>';
    for (
$i = 0, $j = count($csv_line); $i < $j; $i++) {
        print
'<td>'. str_replace (";\"", "<br />", $csv_line[$i]).'</td>';
    }
    print
"</tr>\n";
}
print
'</table>\n';*/
fclose($fp) or die("can't close file");

$bas = file_get_contents ('filename');
print
"<table border=\"1\">\n";
$lines = explode("\n", $bas);
foreach (
$lines as $line) {
    print
'<tr>';
   
$line = ltrim($line, "\"");
   
$line = rtrim($line, "\"");
   
$line = rtrim($line);
   
$out = str_replace("\";\"", "<br />", $line);
   
$out = str_replace("\",\"", "</td><td>", $out);
    print
'<td>' . $out . '</td>';
        print
"</tr>\n";

};
print

'</table>\n';

?>
Tags: |

Reply

The content of this field is kept private and will not be shown publicly.
  • Use [# ...] to insert automatically numbered footnotes. Textile variant.
  • Use [fn]...[/fn] (or <fn>...</fn>) to insert automatically numbered footnotes.
  • You may insert videos with [video:URL]
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Allowed HTML tags: <a> <b> <dd> <dl> <dt> <i> <li> <ol> <u> <ul><p> <img> <table> <tr> <td><strong><em><sup><div><fn><h1><h2><h3><h4><blockquote><img style="">
  • Web page addresses and e-mail addresses turn into links automatically. (Better URL filter.)

More information about formatting options