1
\$\begingroup\$

I wrote this to pull one column of data from a csv file, divide each of the results in 2, and then format it as JSON so I can do stuff with it in a web app. It works, but it feels wonky and weird. Is there a better way to do this?

$fname = "subjects.csv";

$half = array();
$otherkeys = array();
$records = array();


if (($handle = fopen($fname, "r")) === FALSE) {
    exit;
}

/* First line is header with keys */
$keys = fgetcsv($handle);

echo '[';  //added the '['. here to get a propoerly formatted JSON response, not sure why I needed to but I did
while (($data = fgetcsv($handle)) !== FALSE) {
    $half[] = ''.$data[0]/2;    //added the ''. here to get a propoerly formatted JSON response, not sure why I needed to but I did
    $otherkeys[] = $keys[0];
    $records = array_combine($otherkeys, $half);
    $response = json_encode($records);
    echo $response; 
}
fclose($handle);
echo ']';  //added the ']'. here to get a properly formatted JSON response, not sure why I needed to but I did

Any thoughts are much appreciated.

\$\endgroup\$
2
  • \$\begingroup\$ It doesn't look like StackOverflow likes tabs in code. Interesting. \$\endgroup\$
    – FakeRainBrigand
    Dec 11 '11 at 0:11
  • \$\begingroup\$ sorry- it is bad form to ask this kind of question here? why? i'll check out the other site. thanks. \$\endgroup\$
    – user1028228
    Dec 11 '11 at 0:44
2
\$\begingroup\$

The reason you needed the '[' and ']' was to put the array around the records. A better way of doing it is building the array of records in php and then encoding that. Here is what I would do:

$fname = "subjects.csv";

if (($handle = fopen($fname, "r")) === FALSE) {
    exit;
}

$records = array();

/* First line is header with keys */
$keys = fgetcsv($handle);

while (($data = fgetcsv($handle)) !== FALSE) {
   $data[0] /= 2;
   $records[] = array_combine($keys, $data);
}

fclose($handle);

echo json_encode($records);
\$\endgroup\$
0
\$\begingroup\$

try using json_encode instead. Just get the data you want into a php array as you are already doing.

\$\endgroup\$
1
  • \$\begingroup\$ I asked my question poorly. Using json_encode is really handy when I don't want to change anything in the csv file, but if I need to do any operations on the columns... say remove characters or do math or something... I'm confused about the approach. \$\endgroup\$
    – user1028228
    Dec 11 '11 at 0:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy