Manipulate .csv files using (fgetcsv ()) php

1

I'm looking for a way to compare and add data to a csv file using php.

The moment this code has been achieved using

  

fgetcsv ()

Although it does not work 100% because I can not solve some details:

This is the content of "datos.csv"

15,carlos
28,fran
36,luis
44,norlan

This is the code that tries to compare results:

<?php
$id = '36';
$f = fopen("datos.csv", "r");
$result = false;
while ($row = fgetcsv($f, 0, ",")) {
        if ($row[0] == $id) {
            $result = $row[1];
            break;
        }
    }
    fclose($f);
echo $result;

?>

What I'm looking for is to compare the variable $ id with all columns A if it finds it Returns the data in column B.

Still does not work I hope some idea.

Another fact that interests me is how to add the value of $ id that does not find in the file "datos.csv" to column A and another value to column B.

    
asked by BotXtrem Solutions 02.10.2017 в 20:47
source

1 answer

0

Looking for a solution in san google I found information and this is the correct way:

$s= '36';
$f = fopen("demos.csv", "r");
$result = false;
while ($row = fgetcsv($f, 0, ",")) {
        if ($row[0] == $s) {
            $result = $row[1];
            break;
        }
    }
    fclose($f);
echo $result;

and to store the data is used this way:

$id = '1';
$name= 'alfredo';

$file = fopen('demos.csv', 'a');
fputcsv($file, array($id, $name));
fclose($file);

I hope it will be useful to someone Saludes

    
answered by 03.10.2017 / 03:47
source