PHP脚本从CSV文件创建XML文件,但内容为空。

huangapple go评论66阅读模式
英文:

PHP script creates XML files from CSV's but holds 0 contents

问题

我已经创建了一个PHP脚本,用于读取19个CSV文件并规范化数据 - 不保存重复数据(站点ID、名称和地理编码),只保存每个记录中具有值的属性。我已经打印了CSV文件,以确保它们在脚本中加载,但是脚本生成的data-site-id文件内容为空?

<?php

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

// CSV文件列表
$csvFiles = [
    'data-203.csv',
    'data-206.csv',
    'data-209.csv',
    'data-270.csv',
    'data-213.csv',
    'data-215.csv',
    'data-271.csv',
    'data-375.csv',
    'data-395.csv',
    'data-447.csv',
    'data-452.csv',
    'data-463.csv',
    'data-500.csv',
    'data-501.csv',
    'data-672.csv',
    'data-188.csv',
    'data-209.csv',
    'data-481.csv',
    'data-228.csv',
    'data-459.csv',
];

// 遍历每个CSV文件
foreach ($csvFiles as $csvFile) {
    $csvFilePath = __DIR__ . '/' . $csvFile;

    // 打开CSV文件
    if (($handle = fopen($csvFilePath, 'r')) !== false) {
        // 创建XMLWriter实例
        $xmlWriter = new XMLWriter();
        $xmlWriter->openURI(csvFileToXmlFile($csvFile));
        $xmlWriter->startDocument('1.0', 'UTF-8');
        $xmlWriter->startElement('data');

        // 逐行读取CSV文件
        while (($data = fgetcsv($handle)) !== false) {
            // 跳过空行
            if (count($data) === 0) {
                continue;
            }

            // 确保数组具有必要的索引
            if (count($data) >= 4) {
                // 提取必要的数据
                $stationId = $data[0];
                $name = $data[1];
                $geocode = $data[2];
                $attribute = $data[3];

                // 检查属性是否具有值
                if (trim($attribute) !== '') {
                    // 开始XML记录元素
                    $xmlWriter->startElement('record');
                    $xmlWriter->writeAttribute('station_id', $stationId);
                    $xmlWriter->writeAttribute('name', $name);
                    $xmlWriter->writeAttribute('geocode', $geocode);
                    $xmlWriter->writeAttribute('attribute', $attribute);
                    // 结束XML记录元素
                    $xmlWriter->endElement();
                }
            }
        }

        // 关闭XML元素和文件
        $xmlWriter->endElement();
        $xmlWriter->endDocument();
        $xmlWriter->flush();
        fclose($handle);

        // 输出成功消息
        $xmlFile = csvFileToXmlFile($csvFile);
        echo "XML文件成功生成:$xmlFile\n";
    }
}

// 将CSV文件名转换为XML文件名的函数
function csvFileToXmlFile($csvFile) {
    $fileParts = pathinfo($csvFile);
    $xmlFile = $fileParts['filename'] . '.xml';
    return $xmlFile;
}

?>

正如提到的,我已经打印了CSV文件以确保它们在目录中被读取。我还将 $xmlWriter->openURI($csvFileToXmlFile($csvFile)); 更改为 $xmlWriter->openURI(csvFileToXmlFile($csvFile));。之前在52和53行出现的Undefined offset 2和3的错误也已经消失。

CSV的示例图像,不确定如何发送:
查看图像

空白的XML文件 - data-481.xml:
查看XML

期望的XML

英文:

I have created a php script to read through 19 csv files and normalises the data - not holding repeating data (station id, name & geocode) and only holding the attributes for each record which have values. I have printed the csv's to make sure the are loading within the script and the script also makes the data-site-id files but contains 0 contents within the file?


&lt;?php
ini_set(&#39;display_errors&#39;, &#39;1&#39;);
ini_set(&#39;display_startup_errors&#39;, &#39;1&#39;);
error_reporting(E_ALL);
// List of CSV files
$csvFiles = [
&#39;data-203.csv&#39;,
&#39;data-206.csv&#39;,
&#39;data-209.csv&#39;,
&#39;data-270.csv&#39;,
&#39;data-213.csv&#39;,
&#39;data-215.csv&#39;,
&#39;data-271.csv&#39;,
&#39;data-375.csv&#39;,
&#39;data-395.csv&#39;,
&#39;data-447.csv&#39;,
&#39;data-452.csv&#39;,
&#39;data-463.csv&#39;,
&#39;data-500.csv&#39;,
&#39;data-501.csv&#39;,
&#39;data-672.csv&#39;,
&#39;data-188.csv&#39;,
&#39;data-209.csv&#39;,
&#39;data-481.csv&#39;,
&#39;data-228.csv&#39;,
&#39;data-459.csv&#39;,
];
// Loop through each CSV file
foreach ($csvFiles as $csvFile) {
$csvFilePath = __DIR__ . &#39;/&#39; . $csvFile;
// Open the CSV file
if (($handle = fopen($csvFilePath, &#39;r&#39;)) !== false) {
// Create an XMLWriter instance
$xmlWriter = new XMLWriter();
$xmlWriter-&gt;openURI(csvFileToXmlFile($csvFile));
$xmlWriter-&gt;startDocument(&#39;1.0&#39;, &#39;UTF-8&#39;);
$xmlWriter-&gt;startElement(&#39;data&#39;);
// Read the CSV file line by line
while (($data = fgetcsv($handle)) !== false) {
// Skip empty lines
if (count($data) === 0) {
continue;
}
// Ensure the array has the necessary indexes
if (count($data) &gt;= 4) {
// Extract the necessary data
$stationId = $data[0];
$name = $data[1];
$geocode = $data[2];
$attribute = $data[3];
// Check if the attribute has a value
if (trim($attribute) !== &#39;&#39;) {
// Start XML record element
$xmlWriter-&gt;startElement(&#39;record&#39;);
$xmlWriter-&gt;writeAttribute(&#39;station_id&#39;, $stationId);
$xmlWriter-&gt;writeAttribute(&#39;name&#39;, $name);
$xmlWriter-&gt;writeAttribute(&#39;geocode&#39;, $geocode);
$xmlWriter-&gt;writeAttribute(&#39;attribute&#39;, $attribute);
// End XML record element
$xmlWriter-&gt;endElement();
}
}
}
// Close XML elements and file
$xmlWriter-&gt;endElement();
$xmlWriter-&gt;endDocument();
$xmlWriter-&gt;flush();
fclose($handle);
// Output success message
$xmlFile = csvFileToXmlFile($csvFile);
echo &quot;XML file generated successfully: $xmlFile\n&quot;;
}
}
// Function to convert CSV file name to XML file name
function csvFileToXmlFile($csvFile) {
$fileParts = pathinfo($csvFile);
$xmlFile = $fileParts[&#39;filename&#39;] . &#39;.xml&#39;;
return $xmlFile;
}
?&gt;

As mentioned, I have printed the csv's to make sure they are being read within the directory. I also changed the $xmlWriter->openURI($csvFileToXmlFile($csvFile)); to $xmlWriter->openURI(csvFileToXmlFile($csvFile));. I have been getting Undefined offset 2 & 3. Line 52 & 53 error before hand too, these have subsided.

Sample image of csv, wasn't sure how to send it
https://drive.google.com/file/d/1EUHN4RCJFq-XrIBQNvZphh7vxZDdbf_R/view?usp=share_link

Blank XML - data-481.xml
https://drive.google.com/file/d/1pEinOeosPQQRoeQoJHfEb6L_80iD5bqr/view?usp=share_link

desired XML

答案1

得分: 1

你必须学会仔细查看你的数据。csv 文件实际上是 ssv 文件,即"分号分隔值"文件。

你只需更改代码中的这行来让 fgetcsv() 知道分隔符是 ;

while (($data = fgetcsv($handle, 10000, ';')) !== false) {

数据文件 "data-481.csv" 的第二个问题是,对于所有行,$data[1]$data[2]$data[3] 列都为空。

因此,以下代码:

$attribute = $data[3];
if (trim($attribute) !== '') {

用于控制是否将该行写入 XML 文件失败,因此没有数据被写入。

英文:

You must learn to look closely at your data. The csv files are in fact ssv files "SemiColon seperated value" files

All you need to do is change this line of code to let fgetcsv() know the seperator is a ;

    while (($data = fgetcsv($handle,10000,&#39;;&#39;)) !== false) {

Second Issue with data-481.csv

the $data[1], $data[2], $data[3] columns are all empty for all lines

So

$attribute = $data[3];
if (trim($attribute) !== &#39;&#39;) {

which controls whether the row gets written to the xml file fails, so no data is written

huangapple
  • 本文由 发表于 2023年5月18日 02:06:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275027.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定