Php 如何在slim 3中使用fopen()fwrite()创建文件
我有一个应用程序,我上传了一个xml文件,然后将其转换为json,其中json文件是在控制器内部使用fopen(),fwrite()php函数创建的。我的问题是我一直在制作json文件时遇到问题。我不知道是什么问题,但相同的代码运行在基本php上,在slim 3框架中不起作用 示例代码如下:Php 如何在slim 3中使用fopen()fwrite()创建文件,php,fopen,slim,fwrite,slim-3,Php,Fopen,Slim,Fwrite,Slim 3,我有一个应用程序,我上传了一个xml文件,然后将其转换为json,其中json文件是在控制器内部使用fopen(),fwrite()php函数创建的。我的问题是我一直在制作json文件时遇到问题。我不知道是什么问题,但相同的代码运行在基本php上,在slim 3框架中不起作用 示例代码如下: $files = $request->getUploadedFiles(); if (empty($files['file'])) { throw new Exception('Expect
$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_名称只会得到exam_结果
那么,我怎样才能使这个代码工作呢?或者,如果有其他可能的方法,请帮助您没有关闭该文件
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
我没有看到任何读取xml的代码。试试你好。。。虽然xml部分可以工作,但我已经包含了xml部分,不起作用的是创建json文件然后写入。我的问题是我无法使用fopen()创建json文件,而使用fwrite()写入json文件请参见$json
变量。我找不到初始化它的代码。还要确保您有正确的权限来编写文件。$json是xml文件中转换的值,我已经更新了关于这个问题的代码