-1

i have an application where i upload a xml file then it is coverted into json where the json file is being created inside the controller using fopen(), fwrite() php functions. my problem is i keep having a problem on making the json file. i dont know what is the problem, but the same code runs on basic php, it doesnt work in slim 3 framework.

Sample code below:

$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);
       }
...

the $file_name gets its getClientFilename() from the xml file uploaded. so lets say i uploaded "exam_results.xml" the $file_name will only get exam_results.

so how can i make this code work? or if any other way is possible please help

zedling
  • 638
  • 8
  • 28
Emil Kitua
  • 59
  • 8

1 Answers1

0

You are not closing the file

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 {

move the fclose before the return

zedling
  • 638
  • 8
  • 28