0

Is is possible to create a select menu in HTML from a CSV file? I have no idea how to go about this.

So I have a CSV that has two columns and multiple values, is there any way I can loop through the CSV file with PHP and output HTML, I have tried this so far.

$row = 1;
    if (($handle = fopen($_SERVER['DOCUMENT_ROOT']."/service/regions.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 133, ",")) !== FALSE) {
            $num = count($data);
            $row++;
            for ($c=0; $c < $num; $c++) {
                echo "<option value='".$data[$c]."'>".$data[$c]."</option>";
            }
        }
        fclose($handle);
    }

However this is giving the following output,

 <select>
    <option value='AB'>AB</option>
    <option value='Aberdeenshire'>Aberdeenshire</option>
    <option value='AG'>AG</option>
    <option value='Angus'>Angus</option>
    <option value='AM'>AM</option>
    <option value='Armagh'>Armagh</option>
 </select>

What I am wanting is to get the output like this,

<option value="AB">Aberdeenshire</option>

Where am i going wrong?

1
  • "AB", "Aberdeenshire", "AG", "Agath" etc Commented Oct 30, 2012 at 16:51

2 Answers 2

1

All you need is

$handle = fopen(__DIR__ . "/service/regions.csv", "r");
echo "<select>";
if ($handle !== FALSE) {
    $row = 0;
    while ( ($data = fgetcsv($handle, 133, ",")) !== FALSE ) {
        printf('<option value="%s">%s</option>', $data[0], $data[1]);
    }
    fclose($handle);
}
echo "</select>";

Output

<select>
    <option value="AB">Aberdeenshire</option>
    <option value="AG">Angus</option>
    <option value="AM">Armagh</option>
</select>
Sign up to request clarification or add additional context in comments.

Comments

1

$data[$c][0] will return the first column, $data[$c][1] will return the second column and so on. So just replace $data[$c] with the correct variable for your column.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.