通过PHP从CSV获取数据

时间:2016-03-18 08:33:31

标签: php html csv

我有一个csv文件,包含三列和Name,month和vastses。文件名是:name.csv。文件格式是这样的。

NAME    MONTH   EXPANSES
JHON    JAN     200
GATES   JAN     150
JHON    MAR     150
BILL    APP     100

虽然我有一个php文件:name.php,它将从csv文件中获取所需的数据,而sours代码是:

<?php
$x="JHON"; // to be checked in the first column
  $handle = fopen("name.csv","r")or die("file dont exist");
  $output = '';
   while (!feof($handle )){
    $data = fgetcsv($handle,4096,",");
        if(($data[0] ==$x)){
           $output .= sprintf( "Month: %s     Expanses: %d)<br>", 
           $data[1], $data[2]);
        }
    }
echo $output;
fclose($handle);
?>

我想用以上代码来解析名称为“JHON”的位置,结果如下。

Month:  JAN            Expanses:  200 
Month:  MAR           Expanses:  150 
Month:  AUG           Expanses:  250

但我想要的是:JHON的扩展和底部的总支出:金额

MONTH WISE EXPANSES OF JHON 
Month:  JAN            Expanses:  200 
Month:  MAR           Expanses:  150 
Month:  AUG           Expanses:  250

TOTAL EXPANCES:   600

有人可以帮我纠正php代码吗?

2 个答案:

答案 0 :(得分:0)

使用以下功能

function fetchCSV($filename, $header = true, $delimiter = ',') 
{
    if (!file_exists($filename) || !is_readable($filename)) 
    {
        return FALSE;
    }
    $data = array();
    $header_data = array();

    if (($handle = fopen($filename, 'r')) !== FALSE) 
    {
        $r = 0;
        while (($row = fgetcsv($handle, 0, $delimiter)) !== FALSE) 
        {
            if ($header && $r == 0) 
            {
                $header_data = $row;               
            } 
            else 
            {
                if ($header)
                {
                    for($i = 0; $i < count ($row); $i++)
                    {
                        $data[$r][$header_data[$i]] = $row[$i];
                    }
                }
                else
                {
                    $data[$r] = $row;
                }
            }
            $r++;
        }
        fclose($handle);
    }
    return $data;
}

$data = fetchCSV("file.csv", true);

答案 1 :(得分:0)

实际上,您已经从CSV中提取数据。据我所知,你只想在顶部添加一个标题,在底部添加一个总和。

为什么不做这样的事情?

<?php
    $x="JHON"; // to be checked in the first column
    $handle = fopen("name.csv","r") or die("file doesn't exist");
    $output = '';
    $total = 0;

    while (!feof($handle )){
        $data = fgetcsv($handle, 4096, ",");
        if(($data[0] == $x)){
            $output .= sprintf( "Month: %s     Expenses: %d)<br>", $data[1], $data[2]);

            $total += $data[2];
        }
    }

    fclose($handle);

    echo "MONTHLY EXPENSES OF " . $x . "<br/><br/>";
    echo $output . "<br/><br/>";
    echo "TOTAL EXPENSES:   " . $total;
?>

备注2:这是“费用”,“exp a n c e”不是单词