Search code examples
phpformscsvparsingfgetcsv

PHP equivalent to excel INDEX MATCH when parsing CSV


I'm working on a quick project where I'm creating a php webpage that can be accessed from any browser. I only know the very basics of PHP functions so need some help.

What I'm trying to see if I can do is create a file where my colleagues can type in the product code and the form will bring up relevant information about a product. The difficulty is that the information will be managed on excel, but uploaded to the server as a CSV when the information needs updating.

I'm basically looking for a piece of code that does the following:

  1. Webpage gets the product code using POST
  2. PHP parses the first column of the spreadsheet and searches for the product code
  3. On finding the product code, it then returns the row number
  4. PHP then parses the row as an array
  5. I then print the array out in the webpage as needed.

The POST function all works fine, but on the parsing, the best I've got so far is this:

<?php
if ( $code == "") { $codechk = $blank; } else { $codechk = $code; }
$ch = fopen("https://focus-8.com/sites/ds/prodinfo.csv", "r");
$header_row = fgetcsv($ch);

/* This will loop through all the rows until it reaches the end */
while($row = fgetcsv($ch)) { if (in_array($codechk, $row)) { echo '<div>' . implode(' | ', $row) . ' </div>'; } } ;

$code is the product code from the form

$blank is a placeholder that forces an error message if the code doesn't exist.

When I enter the product code in the form, this correctly prints the right row. However my knowledge isn't advanced enough to work out how to pull this into an array rather then print it all at once.

Once I have it in an array, I'll print it in a table like so:

<table>
    <tr>
      <td>Product Code </th>
      <td> <?php echo $prodinfo[0] ?> </th>
    </tr>
    <tr>
      <td>Product Name</td>
      <td> <?php echo $prodinfo[1] ?> </td>
    </tr>
    <tr>
      <td>Product Weight</td>
      <td> <?php echo $prodinfo[2] ?> </td>
    </tr>
</table>

Any help gladly appreciated, thanks!


Solution

  • $line[0] Here 0 indicate product_code column number and comparing with product_code number, Change product_code column number as mentioned in your csv

    if($code!=''){
        $ch = fopen("https://focus-8.com/sites/ds/prodinfo.csv", "r");
        // $file = fopen('http://localhost/stackoverflow/test.csv', 'r');
        while (($line = fgetcsv($ch)) !== FALSE) {
          //$line is an array of the csv elements
          if($line[0]==$code){ // Here `0` indicate product_code column number and comparring with product_code number
              $product_code_array = $line;
          }
        }
        print_r($product_code_array); // Here you get all values of that product_code
        fclose($ch);
    }