Skip to content
Advertisement

Fatal error when trying to Parse a XML file to CSV in PHP

I am stuck on a bit of code for my program, where I am attempting to convert a XML document to CSV using a function in PHP. The code for the function is:

function createCsv($xml, $f)
    {
        foreach ($xml->children() as $item) 
        {
            $hasChild = (count($item->children()) > 0) ? true : false;
            if (!$hasChild) 
            {
                $put_arr = array($item->getName(), $item);
                fputcsv($f, $put_arr, ',', '"');
            } 
            else 
            {
                createCsv($item, $f);
            }
        }
    }

And I am calling it in the main script here:

if (file_exists($FilePath))
        {    
            echo "Converting, please stand by /n";

            $xml = $_FILES;
            $f = fopen('.csv', 'w');
            createCsv($xml, $f);
            fclose($f);
            //calling function to convert the xml file to csv

            $UploadDirectory = $UploadDirectory . basename($_FILES["fileToUpload"]["tmp_name"]);
            if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $UploadDirectory))
            {
                echo "The file has been uploaded and converted. Please click the link below to download it";
                echo '<a href="'.$UploadDirectory.'">'.$File.'</a>';
                //giving link to click and download converted CSV file
            }
            else
            {
                echo "There was a problem uploading and converting the file. Please refresh the page and try again.";
            }
        }

the error message I get when running the script through XAMPP is:

Fatal error: Uncaught Error: Call to a member function children() on array in C:xampphtdocsXMLtoCSVconvert.php:4 Stack trace: #0 C:xampphtdocsXMLtoCSVconvert.php(73): createCsv(Array, Resource id #3) #1 {main} thrown in C:xampphtdocsXMLtoCSVconvert.php on line 4

Line 4 that it is referencing is the foreach statement in the createCSV function. I am really at a loss, and very new to PHP. I have had to teach myself PHP with mixed results, and any assistance would be highly appreciated.

Advertisement

Answer

You are considering $_FILES as the xml file, which is incorrect. $_FILES is an associative array of uploaded files. You need to open the file and read the data. To do so you can use simplexml_load_file:

$xml = simplexml_load_file($_FILES["fileToUpload"]["tmp_name"]);
createCsv($xml, $f);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement