Home > other >  Creating pages from a csv file
Creating pages from a csv file

Time:10-19

I've created a page that grabs data from a CSV (http://liamjken.com/aim-parse/aim-websites-new.csv) and displays it on this page http://www.liamjken.com/aim-parse/parse.php?17

?17 references the row in the csv file. so if I change that to ?10 it pulls the info from a different row.

What I would like to do instead of using the row number is use the $vin_num value. so if I put ?1FMCU9GD9KUC40413 at the end of the URL it would display the row that contains that Number.

here is the code I have currently, its basically cobbled together from multiple different trends I found so if you notice other potential problems id be happy to hear about them.

<?php
$qstring = $_SERVER['QUERY_STRING'];
$row = $qstring; // The row that will be returned.
$data = get_row('aim-websites-new.csv', $row);
'<pre>'.print_r($data).'</pre>';

function get_row($csv, $row) {
    $handle = fopen("$csv", 'r');
    $counter = 0;
    $result = '';
    while ( ($data = fgetcsv($handle)) !== FALSE ) {
        $counter  ;
        if ( $row == $counter ) {
          $vin_num="$data[12]";
          $model="$data[10]";
          $make="$data[9]";
          $year="$data[8]";
          ob_start();
?>

<h1>VIN: <?php echo $vin_num; ?></h1>
<h1>Year: <?php echo $year; ?></h1>
<h1>Make: <?php echo $make; ?></h1>
<h1>Model: <?php echo $model; ?></h1>

 
<?php
$output = ob_get_clean();
ob_flush();

return $output;
        }
        
    }
}
 


 ?>

CodePudding user response:

<?php

function extract_data($file)
{
    $raw = file($file); // file() puts each line of file as string in array
    $keys = str_getcsv(array_shift($raw)); // extract the first line and convert into an array
    
    // Look through the rest of the lines and combine them with the header
    $data = [];
    foreach ($raw as $line) {
        $row = str_getcsv($line);
        $data[] = array_combine($keys, $row);
    }

    return $data;
}

function get_record($data, $vin)
{
    foreach ($data as $record) {
        if ($record['VIN'] === $vin)
            return $record;
    }
    return null;
}

$data = extract_data('aim-websites-new.csv');
$vin = $_SERVER['QUERY_STRING'];
if (empty($vin)) {
    echo '<h1>No VIN provided</h1>';
    exit;
}

$record = get_record($data, $vin);

if ($record === null) {
    echo '<h1>No record found</h1>';
    exit;
}

echo '<h1>' . $record['VIN'] . '</h1>';
echo '<h1>' . $record['Year'] . '</h1>';
echo '<h1>' . $record['Make'] . '</h1>';
echo '<h1>' . $record['Model'] . '</h1>';

echo '<pre>' . print_r($record, true) . '</pre>';

If you don't trust that the records will have valid VINs, you can use the code posted here to validate: How to validate a VIN number?

  • Related