Best way: parse CSV file and go to the front end using AJAX
I have a CSV file that is updated on my server where a PHP script will parse and return the output to JavaScript via AJAX.
The CSV file has two lines. The first line contains the column names and the second line contains the data. I am trying to write a script that will parse it into a form that will be used by Javascript to generate text boxes and labels filled with this data. The current method I have is the following:
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 see many opportunities for general improvement, feel free to point them out. But the main question is that json_encode will be all I need. Anything more efficient? Best idea?
Thanks everyone
source to share
As Lukasz Lalinski wrote in his comment on the answer csl is a friend of yours ( not available until PHP 5.3 by the way). fgetcsv()
str_getcsv()
The code should be simple: (error handling remains in 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 the CSV file:
id,name,value
1,first,value1
2,second,value2
3,third,value3
this will give you the 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 ...
source to share
I would rather use str_getcsv () / fgetcsv () and then json_encode () . In between, you can always shuffle the data to output the displayed JSON the way you want.
In general, it is best to use library functions if available.
source to share