Joshc
Joshc

Reputation: 3853

PHP Loop - Extract Data from CSV and array with echo'd HTML

This is a totally experimental question, but if answered it will save me hours of manual HTML mark up.

In theory it should work, but can appreciate advice if I'm talking rubbish.

I need a loop to pull column data from columns in a CSV spreadsheet, and echo them in HTML mark up.

I can't write PHP but this is how I envisage the loop work...

<?php

    // here it needs to load the CSV file and get the column data and output them as variables (I guess)

echo <div id="interactive-map">

    // here a loop needs to begin to output this line off HTML...
    // with the arrayed variables...

<div id="[varible-1]" class="[varible-2]" title="[varible-3]"><span>[varible-3]</span></div>

    // loop finished once no more rows left in CSV

echo </div>

?>

So the result should look like this...

<div id="interactive-map">

    <div id="1" class="free" title="Uber"><span>Uber</span></div>
    <div id="2" class="free" title="Howdy"><span>Howdy</span></div>
    <div id="3" class="free" title="Love"><span>Love</span></div>
    <div id="4" class="free" title="Gimme"><span>Gimme</span></div>
    <div id="5" class="free" title="Totally"><span>Totally</span></div>
    <div id="6" class="free" title="Spank"><span>Spank</span></div>

</div>

The CSV files looks like this...


(source: motocom.co.uk)

Any help or advice would be TRULY amazing! Thanks

// UPDATE BELOW FOLLOWING FIRST ANSWER

My CSV below viewed as text...

id,class,name
1,free,Uber
2,free,Howdy
3,free,Love
4,free,Gimme
5,free,Totally
6,free,Spank

The PHP below...

    <?php

        $file = fopen('file.csv', 'r');
        $fields = array();

        if ($file) {
        while (($data = fgetcsv($file)) !== false) {

            if(empty($fields)) {
                $fields = $data;
                    continue;
                }


            $row = array_combine($fields, $data);

            $output = sprintf("% is ID, % is CLASS, % is NAME",
                $row['id'],
                $row['class'],
                $row['name']);

            echo $output;

            }

        fclose($file);
    }

?>

It's not quite working properly, what am I doing wrong?

With regards to adding the HTML, I put the mark up inside where the echoed text is and it gets confused :-/

It is echoing stuff but not the desired info from the csv.

Upvotes: 1

Views: 7233

Answers (1)

Jon
Jon

Reputation: 437404

To read the file, the easiest is to use the built-in fgetcsv in a loop. You can cook up your own parsing code, but it's really thankless work to make it behave correctly in the presence of field delimiters and escaped characters.

After reading the names of the CSV fields (first iteration) and their values for each row (subsequent iterations), you can use sprintf or vsprintf to easily construct an HTML string to output.

For example:

$file = fopen('php://stdin', 'r'); // or open any other file you want
$fields = array(); // this holds the name of the fields, read from the 1st row

if ($file) {
    while (($data = fgetcsv($file)) !== false) {
        // If this is the first row, we assume it holds field names.
        // So just remember what they are and loop to the next.
        if(empty($fields)) {
            $fields = $data;
            continue;
        }

        // Subsequent rows are assumed to contain data.
        // array_combine associates the data in the current row with the field
        // names from the first row, allowing us to refer to them using those
        // names and be independent of the order the fields appear in the input.
        $row = array_combine($fields, $data);

        // Format output conveniently with sprintf
        $output = sprintf("%s is %d years old.\n",
                          $row['name'],
                          $row['age']);
        echo $output;
    }
    fclose($file);
}

See it in action.

Upvotes: 2

Related Questions