PHP 脚本写入了子集,但是在向根添加属性时,它崩溃了

问题描述 投票:0回答:1

我制作了这个 php 脚本来将 CSV 文件转换为 XML 文件。我有一个 for each 循环来处理本节中的记录和内容。产生以下结果。

current results

我一直在添加相同的循环以包含根站内的详细信息以包含如图所示的结果

desired results

但是当我添加这个相同的循环来读取根时,它似乎中断了,似乎崩溃了。即使在反复试验中,从代码中的这一部分开始并删除但无济于事。

同样在此一些条目 (data-481.xml) 中是空的,但在谷歌驱动器中有 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 中,并具有所需的

php xml csv fgets xmlwriter
1个回答
0
投票

进行了一些更改,首先确保有效的 XML 文件,其次从正确的位置提取正确的数据

// 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

        /* You cant write the Station element until you have read the csv file
            as it needs data for its properties from there
            So moved inside the while loop
        */

        $xmlWriter = new XMLWriter();
        $xmlWriter->openURI(csvFileToXmlFile($csvFile));
        $xmlWriter->startDocument('1.0', 'UTF-8');

        $flagFirstLineWritten = false;      // control writing on Station element only once
        
        while (($data = fgetcsv($handle,10000,';')) !== false) {
            // Skip empty lines
            if (count($data) === 0) {
                continue;
            }
            /*
                output the Station element with its properties only once
            */
            if ( ! $flagFirstLineWritten ) {
                $xmlWriter->startElement('Station');
                $xmlWriter->writeAttribute('id',        $data[4]);
                $xmlWriter->writeAttribute('name',      $data[17]);
                $xmlWriter->writeAttribute('geocode',   $data[18]);
                $xmlWriter->endAttribute();
                $flagFirstLineWritten = true;
            }
            
            // Ensure the array has the necessary indexes
            if (count($data) >= 4) {
                // Extract the necessary data
                /*
                    convert the DATE to a timestamp
                */
                $ts = (new DateTime())->createFromFormat( DateTimeInterface::ISO8601, $data[0]);
                                
                // Check if the attribute has a value
                if (trim($data[3]) !== '') {
                    // Start XML record element
                    $xmlWriter->startElement('rec');
                    $xmlWriter->writeAttribute('ts',    (string)$ts->getTimestamp());
                    $xmlWriter->writeAttribute('nox',   $data[1]);
                    $xmlWriter->writeAttribute('no',    $data[2]);
                    $xmlWriter->writeAttribute('no2',   $data[3]);
                    // End XML record element
                    $xmlWriter->endElement(); // end rec
                }
            }
        }

        $xmlWriter->endElement();   // station element
        $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;
}

结果,示例

<?xml version="1.0" encoding="UTF-8"?>
<Station id="203" name="Brislington Depot" geocode="51.441747180510106, -2.5599558321904605">
    <rec ts="1546326000" nox="18.5" no="12.5" no2="3.75"/>
    <rec ts="1546412400" nox="163.75" no="55.0" no2="71.0"/>
    
    . . .

    . . .
</Station>
© www.soinside.com 2019 - 2024. All rights reserved.