XML
  Home arrow XML arrow Page 3 - Talking business: How I Learned to Love CS...
IBM Rational Software Development Conference
Iron Speed
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Download TestComplete 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
IBM Developerworks
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
XML

Talking business: How I Learned to Love CSV
By: Chris Heilmann
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 6
    2005-07-25

    Table of Contents:
  • Talking business: How I Learned to Love CSV
  • Handing out files in different formats
  • So what is a CSV file and how can I use it?
  • Laziness as a benefit

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    Iron Speed
     
    ADVERTISEMENT

    Free Web 2.0 Code Generator! Generate data entry and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!

    Talking business: How I Learned to Love CSV - So what is a CSV file and how can I use it?
    (Page 3 of 4 )

    A CSV file is a comma separated list of data; each data set is on a new line. The first line contains the headers, explaining what the following elements are. In short, a CSV is a really easy table.

    Saved as employees.csv, this is:

    Name,Surname,Department,Room

    Bob,Houston,Problems,214

    Stephen,Seagull,Cleaning,231

    Arnold,Egger,Security,102

    Eliza,Ihaye,Communications,207

    Back in the days of old, when we used Perl or ancient versions of PHP, we tackled CSV files with Regular Expressions, first splitting the data into an array at the linebreak, and then splitting the lines into data at the comma.

    <?php

    $data=load('employees.csv');

    if($data!='')

    {

                $lines=preg_split("/\n/",$data);

                $headers=preg_split("/,/",$lines[0]);

                echo '<table>';

                echo '<thead><tr>';

                foreach($headers as $h)

                {

                            echo '<th scope="col">'.$h.'</th>';

                }

                echo '</tr></thead>';

                echo '<tbody>';

                for($i=1;$i<sizeof($lines);$i++)

                {

                            $linedata=preg_split("/,/",$lines[$i]);

                            $class=$i%2==0?' class="odd"':'';

                            if($linedata[0]!='')

                            {

                                        echo '<tr'.$class.'>';

                                        foreach($linedata as $l)

                                        {

                                                    echo '<td>'.$l.'</td>';

                                        }

                                        echo '</tr>';

                           }

                }

                echo '</tbody>';

                echo '</table>';

    }

    function load($filelocation)

    {

                if (file_exists($filelocation))

                {

                            $newfile = fopen($filelocation,"r");

                            $file_content = fread($newfile, filesize($filelocation));

                            fclose($newfile);

                            return $file_content;

                }

    }

    ?>

    That works wonders, but soon reaches its limits, as there are dangers:

    • Unix and Windows environments do have different ways of defining a line break.
    • When an editor enters a comma in one of the fields, Excel will add quotation marks around that field data. We need to alter our regular expression to take care of that.
    • Excel offers various versions of CSV to save (Windows, DOS, Macintosh), each with different settings.

    Lucky for us, the PHP developers showed mercy and created fgetcsv(), which tackles most of these issues. On Macintosh systems there might be some trouble still, but there is a workaround – setting the auto_detect_line_endings in the PHP configuration to true .

    Our previous example looks a lot easier when we use this function.

    echo '<table>';

    $row=0;

    $handle = fopen("employees.csv", "r");

    while (($data = fgetcsv($handle, 1000)) != FALSE)

                {

                if($row==0)

                {

                            echo '<thead><tr>';

                            foreach ($data as $c)

                            {

                                        echo '<th scope="col">'.$c.'</th>';

                            }

                            echo '</tr></thead><tbody>';

                } else {

                            $class=$row%2==0?' class="odd"':'';

                            echo '<tr'.$class.'>';

                            foreach ($data as $c)

                            {

                                        echo '<td>'.$c.'</td>';

                            }

                            echo '</tr>';

                }

                $row++;

    }

    fclose($handle);

    echo '</tbody></table>';

    For storing data or exporting it as a CSV, we can use the fputcsv() function. In connection with a proper header (content-type and content-disposition) it will prompt the user to either open our script output in Excel or save it.

    More XML Articles
    More By Chris Heilmann


       · Poorly titled article. I thought it would cover some useful/unusual/clever ways of...
       · 1) I totally agree with CSV not being an Excel format but one Excel can read.2) I...
       · I must agree i'm rather puzzled aswell as to what the usefullness of csv is in this...
       · Read Number Two above?
       · I am completely baffled over this article. I wish I never saw it.
       · As an 'Anonymous Loozah', I read the article which is actually very good.One of...
     

    XML ARTICLES

    - Path, Predicates, and XQuery
    - Using Predicates with XQuery
    - Navigating Input Documents Using Paths
    - XML Basics
    - Introduction to XPath
    - Simple Web Syndication with RSS 2.0
    - Java UI Design with an IDE
    - UI Design with Java and XML Toolkits
    - Displaying ADO Retrieved Data with XML Islan...
    - Widget Walkthrough
    - Introduction to Widgets
    - The Why and How of XML Data Islands
    - Creating an XUL App Installer
    - Overlays in XUL
    - Skinning Your Custom XUL Applications






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway