我有一个处理上传的CSV到临时目录的PHP脚本,然后我有5行代码将CSV转换为JSON。使用file_get_contents()处理上传文件
我的PHP脚本:
if (isset($_FILES['csvList']['type'])) {
$validExtensions = array("csv");
$temporary = explode(".", $_FILES["csvList"]["name"]);
$file_extension = end($temporary);
if (in_array($file_extension, $validExtensions)) {
if ($_FILES["csvList"]["error"] > 0) {
echo "Return Code: " . $_FILES["csvList"]["error"] . "<br/><br/>";
} else {
if (file_exists("/var/www/tmp/" . $_FILES["csvList"]["name"])) {
echo $_FILES["csvList"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
} else {
$sourcePath = $_FILES['csvList']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "/var/www/tmp/".$_FILES['csvList']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
$csvFile = $sourcePath;
$csv = file_get_contents($csvFile);
$csvArray = array_map("str_getcsv", explode("\n", $csvFile));
$csvToJson = json_encode($csvArray);
print_r($csvToJson);
}
}
}
}
$sourcePath = $_FILES['csvList']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "/var/www/tmp/".$_FILES['csvList']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
的问题是在这条线:print_r($csvToJson);
。 这是输出:
[["\/tmp\/phpYeuuBB"]]
这是我的临时文件的文件路径,我究竟做错了什么?
这里是我的CSV是什么样子 -
更新:我的JSON是不正确格式化“和\旁边名
{"data":["[[\"Debra Brown\"],[\"Jacqueline Garza\"],[\"Kenneth Foster\"],[\"Antonio Howell\"],[\"Fred Rogers\"],[\"Robert Stanley\"],[\"Jesse Price\"],[\"Henry Bishop\"],[\"Marilyn Phillips\"],[\"Charles White\"],[\"Dennis Lawrence\"],[\"Nicholas Thompson\"],[\"Chris Graham\"],[\"Louis Dean\"],[\"Katherine Green\"],[\"Janice Peters\"],[\"Bobby Wood\"],[\"Bruce King\"],[\"Diane Mills\"],[\"Jane Fields\"],[\"Amanda Gutierrez\"],[\"Russell Cunningham\"],[\"Judith Matthews\"],[\"Carol Franklin\"],[\"Jose Murray\"],[\"Kathryn Cole\"],[\"Katherine Gardner\"],[\"Lois Woods\"],[\"Andrew Bryant\"],[\"Victor Wright\"],[\"Adam Russell\"],[\"Tina Gilbert\"],[\"Shawn Boyd\"],[\"Wanda Porter\"],[\"Rose Morris\"],[\"John Mccoy\"],[\"Frances Gibson\"],[\"Willie Lopez\"],[\"Chris Reyes\"],[\"Craig Vasquez\"],[\"Diane Simmons\"],[\"Mary Little\"],[\"Patricia Fowler\"],[\"Jane Perkins\"],[\"Juan Brooks\"],[\"Bruce Howard\"],[\"Tammy Richardson\"],[\"Jane Gomez\"],[\"Tammy Matthews\"],[\"Matthew Fox\"],[null]]"]}
应该如何 -
{"data":[["Debra Brown"]]}
当我打印$csv
完美工作的感谢,任何机会你会知道为什么我的JSON在它和引号之前有\ \检查我更新的帖子。 – Kieron606
@ Kieron606首先,如果您打印这些文件,是否在'$ csv'中存在这些斜线?其次,在'str_getcsv()'中会发生什么?也许这是你遇到的问题的一部分。 – Henders
'$ csv'看起来很完美 – Kieron606