我有一个应用程序,我上传一个xml文件,然后它被转换为json,其中使用fopen(),fwrite()php函数在控制器内创建json文件。我的问题是我在制作json文件时遇到问题。我不知道是什么问题,但相同的代码运行在基本的PHP,它不适用于slim 3框架。
示例代码如下:
$files = $request->getUploadedFiles();
if (empty($files['file'])) {
throw new Exception('Expected a file');
}
$file = $files['file'];
$getFile = $file->getClientFilename();
$extension = pathinfo($file->getClientFilename(), PATHINFO_EXTENSION);
//check file extension
if($extension != 'xml') {
$uploadOk = 0;
$error .= 'Not the correct file type';
} else {
$path = $file->moveTo( __DIR__ . '/../../../public/Backup/' . $getFile);
if($path) {
$XMLFilePath = __DIR__ . '/../../../public/Backup/' . $getFile;
//convert xml to json
$fileContents = file_get_contents($XMLFilePath);
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_string($fileContents);
$json = json_encode($simpleXml);
$file_name = pathinfo($file->getClientFilename(), PATHINFO_FILENAME);
$filename = preg_replace('/\\.[^.\\s]{3,4}$/', '', $file_name);
$filename = str_replace(' ', '_', $filename);
$filename = str_replace('.xml', '', $filename);
$jsonFileName = $filename . '_' . str_replace(":", "_", $dateTime);
//join time and file name to create unique file name
$jsonFile = __DIR__ . '/../public/' . $jsonFileName . ".json";
//create json file
$jsonWrite = fopen($jsonFile, "w+");
if(fwrite($jsonWrite, $json)) {
$success .= 'File parsed from xml to json';
return $response->withJson($success, 200);
fclose($jsonWrite);
} else {
// failed to write to json file
$error .= 'failed to write to json file';
return $response->withJson($error, 200);
}
...
$ file_name从上传的xml文件中获取其getClientFilename()。所以假设我上传了“exam_results.xml”,$ file_name只会获得exam_results。
那么我怎样才能使这段代码有效呢?或者如果有其他方式可以请帮助
您没有关闭该文件
if(fwrite($jsonWrite, $json)) {
$success .= 'File parsed from xml to json';
return $response->withJson($success, 200); // return ?
fclose($jsonWrite); // this line never get called!!!
} else {
返回前移动fclose