0

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

Gordon
  • 312,688
  • 75
  • 539
  • 559
Neil Frost
  • 27
  • 1

1 Answers1

0

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 
        ); 
    } 
fullybaked
  • 4,117
  • 1
  • 24
  • 37
  • Yes, but given that description is free text, the chances for it including a comma are pretty high. You better use fgetcsv than explode (as indicated in the tags of the question) – Gordon May 03 '13 at 14:03
  • Hmm, that's a good point. Thanks for the edit as well. Much cleaner... – fullybaked May 03 '13 at 14:09
  • You don't need the explode() call if you're using fgetcsv. You can just pass in the $line as the second param over vprintf as it should be an array of values from the csv file for the line it is currently parsing – fullybaked May 03 '13 at 14:51
  • ok, so I think I'm missing something... this is the full code

    %s

    Posted on %s

    %s

    /article>', $line ); } } fclose($handle); } ?> but its says too few arguments for vprintf
    – Neil Frost May 03 '13 at 15:02
  • So I was getting vprintf too few arguments and found out it's treating each cell in the csv as a new line rather than reading the actual line. – Neil Frost May 03 '13 at 15:36
  • Yeah, that will do it. `var_dump` out line and ensure that it has 3 elements in it that can be merged into the template where the `%s` tokens are. Check out the [fgetcsv](http://php.net/manual/en/function.fgetcsv.php) docs to see how to use the method to get the most out of the csv parsing – fullybaked May 03 '13 at 15:39
  • did the var_dump and it just has the 1 element per line, and not 3 elements – Neil Frost May 03 '13 at 15:45
  • Se edit to my answer, the second code example has changed. – fullybaked May 03 '13 at 15:51