尝试将 XML 文件解析为 PHP 中的 CSV 时出现致命错误

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

我的程序代码卡住了,我试图使用 PHP 中的函数将 XML 文档转换为 CSV。该函数的代码是:

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

我在这里的主脚本中调用它:

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.";
            }
        }

我在 运行 通过 XAMPP 脚本时收到的错误消息是:

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

它引用的第 4 行是 createCSV 函数中的 foreach 语句。我真的很茫然,而且对PHP很陌生。我不得不自学 PHP 结果好坏参半,非常感谢任何帮助。

您将 $_FILES 视为 xml 文件,这是不正确的。 $_FILES 是上传文件的关联数组。您需要打开文件并读取数据。为此,您可以使用 simplexml_load_file:

$xml = simplexml_load_file($_FILES["fileToUpload"]["tmp_name"]);
createCsv($xml, $f);