Katy Katy - 9 months ago 49
HTML Question

PHP to create an HTML Table with URLs from a CSV

I'm very new to PHP (and all server side languages) but I'm trying to teach myself. I have an excel spreadsheet that I need to place on a website as a table. I was able to pull in a csv through PHP to create the HTML table. However, I need the last column ("Links") to contain hyperlinks of the word "Go" that once clicked bring you to its respective unique URL.

I would be incredibly grateful for any help.

Here is my PHP:

<!DOCTYPE html>
<link href="stylesheets/styles.css" rel="stylesheet" />
echo "<table>\n\n";
$f = fopen("market_research.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
echo "<tr>\n";
echo "\n</table></body></html>";


For reference, here is a screencap of my table:
html table

Lastly, here is a screencap of the spreadsheet that I'm using:


Answer Source

Change your for loop like this:

foreach ($line as $cell) {
    echo "<td>";
    if (substr($cell, 0, 4) == "http") { // if the cell starts with http (or https)
        echo "<a href='" . $cell . "'>Go</a>";
    } else {
        echo htmlspecialchars($cell);
    echo "</td>";