开发者

Best Method: Parsing CSV file and Passing back to front end using AJAX

开发者 https://www.devze.com 2022-12-08 12:54 出处:网络
I have a CSV file that is u开发者_StackOverflowplaoded to my server where a PHP script will parse and return output to JavaScript via AJAX.

I have a CSV file that is u开发者_StackOverflowplaoded to my server where a PHP script will parse and return output to JavaScript via AJAX.

The CSV file is made up of two rows. First row contains the column names and the second row contains the data. I am trying to write a script that will parse it in a form that will be usable by Javascript to generate text fields and labels populated with this data. The current method that I have is this:

if ( $_FILES['parameter_file']['tmp_name'] ) {

    $paramfile = fopen($_FILES['parameter_file']['tmp_name'], 'r');
    $header = fgets($paramfile);
    $temp = explode(',', str_replace('"', '', rtrim(ltrim($header))));

    $userdata = fgets($paramfile);
    $temp2 = explode(',', str_replace('"', '', rtrim(ltrim($userdata))));

    for ($k = 0; $k <= sizeof($temp) - 1; $k++) {
        $userparam[strtolower($temp[$k])] = $temp2[$k];
    }

    fclose($paramfile);
}

I can see loads of room for general improvement, feel free to point them out. But the main question is would a json_encode be all I need. Anything more efficient? A better idea?

Thanks all


As Lukáš Lalinský wrote in his comment to csl's answer fgetcsv() is your friend (by the way str_getcsv() is not available prior to PHP 5.3).

The code should be a simple as (error-handling is left to the OP):

$headers   = null;
$rowNum    = 0;
$tableData = array();
$handle    = fopen($_FILES['parameter_file']['tmp_name'], 'r');
while (($data = fgetcsv($handle)) !== false) {
    if ($rowNum == 0) {
        // parsing the CSV header
        $headers = array();
        foreach ($data as $d) {
            $headers[] = $d;
        }
    } else {
        // parsing the data rows
        $rowData = array();
        foreach ($data as $d) {
            $rowData[] = $d;
        }
        $tableData[] = array_combine($headers, $rowData)
    }
    $rowNum++;
}
fclose($handle);

Given a CSV file of:

id,name,value
1,first,value1
2,second,value2
3,third,value3

this will give you a headers-array with

array(
    0 => 'id',
    1 => 'name',
    2 => 'value'
)

and a $tableData-array with

array(
    0 => array(
        'id'    => '1',
        'name'  => 'first',
        'value' => 'value1'
    ),
    1 => array(
        'id'    => '2',
        'name'  => 'second',
        'value' => 'value2'
    ),
    2 => array(
        'id'    => '3',
        'name'  => 'third',
        'value' => 'value3'
    )
)

Adjust the code as needed...


I would rather use str_getcsv() / fgetcsv() and then json_encode(). In between, you can always shuffle the data to make the outputted JSON look as you want.

In general, it's better to use the library functions if they are available.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号