ckportfolio.com - Organizing and Serving Array as CSV

Organizing and Serving Array as CSV

Displaying Data

Now that we have an organized data array under the table variable, we can return to index.php and display the data under <tbody>:

index.php

...

<tbody>

    <? foreach ($table as $row) { ?>

        <tr>
            <td><?= $row[0] ?></td>
            <td><?= $row[1] ?></td>
            <td><?= $row[2] ?></td>
            <td><?= $row[3] ?></td>
        </tr>

    <? } ?>

</tbody>

...

We can see that the page now displays the retrieved data in a table format:

Saving Data as CSV

CSV (Comma-separated values) file is an alternative to Excel files for storing spreadsheet data, and we can conveniently convert our array data to a downloadable file.

Sample

John,Doe,120 jefferson st.,Riverside, NJ, 08075
Jack,McGinnis,220 hobo Av.,Phila, PA,09119
"John ""Da Man""",Repici,120 Jefferson St.,Riverside, NJ,08075
Stephen,Tyler,"7452 Terrace ""At the Plaza"" road",SomeTown,SD, 91234
,Blankman,,SomeTown, SD, 00298
"Joan ""the bone"", Anne",Jet,"9th, at Terrace plc",Desert City,CO,00123

We can return to data.php and create a new variable that serves as the CSV content:

data.php

...

    $csvString = '';
    foreach ($table as $row) {
        $csvString .= implode(", ", $row);
        $csvString .= "\n";
    }

?>

In the above snippet, we are iterating through the table variable again, but this time converting each "row" into a line of comma-separated values and appending to the csvString variable, followed by a line break.

Thanks to the latest development in HTTP standards, we have an ability to treat such internal variables as if they are external files, forcing the user to download them as attachments.

index.php

...

        </tbody>
    </table>

    <a class="btn btn-primary mt-5" href="data:text/csv;charset=utf-8,<?= $csvString ?>">Download CSV</a>

...

Note that we are using a specific syntax to denote that this "link" should be downloaded as a CSV file, as well as the content of this pseudo file, csvString, itself.

We see that the button immediately begins the download process, allowing you to directly download the manually generated CSV file onto the computer. We now have an application that has a capacity of scrape pertinent content from a typical website and organize neatly info a table format.

Fin