尝试在PHP中将XML文件解析为CSV时发生致命错误



我被困在我的程序的一些代码上,我试图使用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: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

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

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

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

相关内容

最新更新