我做了这个php脚本来将CSV文件转换为XML文件。我有一个for each循环来处理这个部分中的记录和内容。这产生以下结果。
current results
我一直在添加相同的循环,以包含根站内的细节,以包含如图所示的结果
desired results
但是当我添加这个相同的循环来读取根时,它似乎中断了,似乎崩溃了。即使尝试和错误,从代码中的这一部分开始并删除,但无济于事。
此外,在此部分中,一些条目(data-481.xml)是空的,但在google drive中,data-481.csv的信息中有行。
空白XML - data-481.csv https://drive.google.com/file/d/1pEinOeosPQQRoeQoJHfEb6L_80iD5bqr/view?usp=share_link
<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
// List of CSV files
$csvFiles = [
'data-203.csv',
'data-206.csv',
'.....'
];
// Loop through each CSV file
foreach ($csvFiles as $csvFile) {
$csvFilePath = __DIR__ . '/' . $csvFile;
// Open the CSV file
if (($handle = fopen($csvFilePath, 'r')) !== false) {
// Create an XMLWriter instance
$xmlWriter = new XMLWriter();
$xmlWriter->openURI(csvFileToXmlFile($csvFile));
$xmlWriter->startDocument('1.0', 'UTF-8');
$xmlWriter->startElement('Station');
// Read the CSV file line by line
while (($data = fgetcsv($handle,10000,';')) !== false) {
// Skip empty lines
if (count($data) === 0) {
continue;
}
// Ensure the array has the necessary indexes
if (count($data) >= 4) {
// Extract the necessary data
$timestamp = $data[0];
$nox = $data[1];
$no2 = $data[2];
$no = $data[3];
// Check if the attribute has a value
if (trim($no) !== '') {
// Start XML record element
$xmlWriter->startElement('rec');
$xmlWriter->writeAttribute('ts', $timestamp);
$xmlWriter->writeAttribute('nox', $nox);
$xmlWriter->writeAttribute('no2', $no2);
$xmlWriter->writeAttribute('no', $no);
// End XML record element
$xmlWriter->endElement();
}
}
}
// Close XML elements and file
$xmlWriter->endElement();
$xmlWriter->endDocument();
$xmlWriter->flush();
fclose($handle);
// Output success message
$xmlFile = csvFileToXmlFile($csvFile);
echo "XML file generated successfully: $xmlFile\n";
}
}
// Function to convert CSV file name to XML file name
function csvFileToXmlFile($csvFile) {
$fileParts = pathinfo($csvFile);
$xmlFile = $fileParts['filename'] . '.xml';
return $xmlFile;
}
?>
我希望将所有文件从CSV转换为XML,并使用所需的<station元素保存<station id=“481 location=“Bath Road”geocode=“51.3453,-2.55434”>
1条答案
按热度按时间0md85ypi1#
进行了一些更改,首先是为了确保XML文件有效,其次是为了从正确的位置提取正确的数据
结果,示例