简体   繁体   中英

PHP custom CSV read, independent echos for different columns and rows

I have a simple CSV with let's say 6 columns.

EDIT: I can't find the mistake in the following, it's to do with selecting a key and using it as a variable I think:

$handle = fopen('hire_pa_amps.csv',"r");
while($values = fgetcsv($handle))
{
foreach('$values[0]' as $value0)
{
    echo($value0);
}
foreach('$values[1]' as $valuepound)
{
    echo('&pound'.$valuepound);
}
echo ('<br>'); }
fclose($handle); 



The data from the CSV file looks like this:
 "H/H ELECTRONICS VX200, 100 watts/channel stereo amplifier",70,30,20
  Electrovoice CP1800,84,36,24

In the meantime I've managed to do it somehow differently (and it works, for now) but I still want to know where the problem is in the code above (how to select a key in a array and manipulate it independently while using foreach). So the solution that I made for now:

$handle = fopen('hire_pa_amps.csv','r') or die("can't open file");

echo('<table class="pricesTable">');
while($csv_line = fgetcsv($handle)) {
    list($column1, $column2, $column3, $column4) = $csv_line;

    echo('<tr>');

    echo    '<td>'.$column1.'</td>'.
            '<td>'.'&pound'.$column2.'</td>'.
            '<td>'.'&pound'.$column3.'</td>'.
            '<td>'.'&pound'.$column4.'</td>';
    echo('</tr>');
    }
fclose($handle) or die("can't close file");
echo('</table>');

If you change your CSV to include column headers and then edit the column selection in the code below then this will work:

function csv_to_array($filename='', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
    return FALSE;

$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
    while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
    {
        if(!$header)
            $header = $row;
        else
            $data[] = array_combine($header, $row);
    }
    fclose($handle);
}
return $data;
}

$csvArray = csv_to_array('hire_pa_amps.csv');
echo "<table>
<tr>
    <th>Product Name</th>
    <th>Price</th>
    <th>Markup</th>
    <th>VAT</th>
</tr>
";
foreach($csvArray as $currentProduct){
    echo "  <tr>
    <td>" . $currentProduct['Product Name'] . "</td>
    <td>" . $currentProduct['Price'] . "</td>
    <td>" . $currentProduct['Markup'] . "</td>
    <td>" . $currentProduct['VAT'] . "</td>
</tr>
";
}
echo "</table>";

I don't think you were thinking about the way the CSV was parsed to an array properly with your foreach() 's, you were trying to loop on $values[0] when you should have been looping on $values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM