【发布时间】:2016-04-15 11:31:17
【问题描述】:
我有一个 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 格式不正确,名称旁边有 " 和 \
{"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
【问题讨论】: