csv PHP脚本写入子集,但当向根添加属性时,它会崩溃

zazmityj  于 2023-05-20  发布在  PHP
关注(0)|答案(1)|浏览(69)

我做了这个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”>

0md85ypi

0md85ypi1#

进行了一些更改,首先是为了确保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>

相关问题