mongodb - Upload a CSV FIle in php and make it as json format -
i have csv file , want upload csv file mongodb. through php function. id handle 1 naveen
2 bos
how can read , make json encoded format in php needed json format
{"id" : "1", "handle" : "naveen"}, {"id" : "2", "handle" : "bos"}
i using code
if (isset($_post['submit'])) { if (is_uploaded_file($_files['filename']['tmp_name'])) { echo "<h1>" . "file ". $_files['filename']['name'] ." uploaded successfully." . "</h1>"; echo "<h2>displaying contents:</h2>"; readfile($_files['filename']['tmp_name']); } $handle = fopen($_files['filename']['tmp_name'], "r"); while (($data = fgetcsv($handle, 1000, ",")) !== false) { $data=json_encode($data); print_r($data); } fclose($handle); print "import done"; } else { print "<form enctype='multipart/form-data' action='upload.php' method='post'>"; print "file name import:<br />\n"; print "<input size='50' type='file' name='filename'><br />\n"; print "<input type='submit' name='submit' value='upload'></form>"; }
the output id,name 1,naveen 2,bos ["id","name"]["1","naveen"]["2","bos"]
needed jsonencoded format this
{"id" : "1", "handle" : "naveen"}, {"id" : "2", "handle" : "bos"}
how can this? please help
$keys=""; $result=array(); while (($data = fgetcsv($handle, 1000, ",")) !== false) { if($keys==""){ $keys = $data; }else{ $output = array(); ($i=0; $i <count($keys) ; $i++) { $output[$keys[$i]]=$data[$i]; } array_push($result, $output); } } echo "<pre>"; print_r(json_encode($result)); echo "</pre>";
Comments
Post a Comment