我有一个csv文件,我想将此csv文件上传到mongoDB。通过PHP功能。
Id句柄
1 Naveen
2博斯
我如何阅读并使其成为PHP中的json编码格式
这是我需要的json格式
{"id" : "1", "handle" : "Naveen"},
{"id" : "2", "handle" : "Bos"}
我正在使用此代码
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 to import:<br />\n";
print "<input size='50' type='file' name='filename'><br />\n";
print "<input type='submit' name='submit' value='Upload'></form>";
}
输出为id,name 1,naveen 2,bos ["id","name"]["1","naveen"]["2","bos"]
我需要的jsonencoded格式是这个
{"id" : "1", "handle" : "Naveen"},
{"id" : "2", "handle" : "Bos"}
我怎么能得到这个?请帮忙
答案 0 :(得分:0)
$keys="";
$result=array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($keys==""){
$keys = $data;
}else{
$output = array();
for ($i=0; $i <count($keys) ; $i++) {
$output[$keys[$i]]=$data[$i];
}
array_push($result, $output);
}
}
echo "<pre>";
print_r(json_encode($result));
echo "</pre>";