Search code examples
phpfgetcsv

fgetcsv formatting individual cells


I have a csv file with this data in it

date,title,description
01/05/2013,Test,This is a test
03/05/2013,Test2,This is another test

I would like to format it like a news article so the html would be something like

<article>
  <h3>$title</h3>
   <h6>Posted on $date</h6>
   <p>$description</p>
</article>
<article>
  <h3>$title</h3>
   <h6>Posted on $date</h6>
   <p>$description</p>
</article>

I get the for each $line bit, but then not sure how to do the rest of it. Lots around about tables, but not this that I can find.

Can someone help out please?

thanks Neil


Solution

  • Something like this should work

    foreach ($csvData as $line) {
        vprintf(
            '<article><h3>%s</h3><h6>Posted on %s</h6><p>%s</p>/article>', 
            explode(',', $line)
        );
    }
    

    Edit based on @Gordon comment, using fgetcsv

    while (($line = fgetcsv($handle, 1000, ",")) !== FALSE) {             
            vprintf( 
                '<article><h3>%s</h3><h6>Posted on %s</h6><p>%s</p></article>', 
                $line 
            ); 
        }