我有一个PHP脚本处理上传的CSV到临时目录,然后有5行代码从CSV转换为JSON。
我的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格式不正确&#34;和\旁边的名字
{"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
答案 0 :(得分:2)
您正在将文件分配给变量$csv
,但之后您正在执行此操作:
$csvArray = array_map("str_getcsv", explode("\n", $csvFile));
变量$csvFile
仍然包含您之前设置为$sourcePath
的文件的文件路径。从file_get_contents()
返回的实际文件字符串位于$csv
。如果您将其更改为如下所示:
$csvArray = array_map("str_getcsv", explode("\n", $csv));
您可能会发现这可以解决您的问题。
以下为the docs
的file_get_contents()答案 1 :(得分:2)
您似乎正在输入CSV到str_getcsv的路径
$csvArray = array_map("str_getcsv", explode("\n", $csvFile));
而不是您的实际CSV内容
$csvArray = array_map("str_getcsv", explode("\n", $csv));